片段被销毁后停止处理程序 [英] Stop handler after the fragment has been destroyed

查看:91
本文介绍了片段被销毁后停止处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Fragment,它设置了ListView并创建了Handler来定期更新Listview.但是,看起来HandlerFragment被销毁后仍然可以运行.

I have a Fragment which sets up a ListView and creates a Handler to update the Listview periodically. However, it looks like the Handler still runs after the Fragment has been destroyed.

以下是代码.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    //boilerplate code

    final Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            assignAdapter();
            handler.postDelayed(this, 15000);
        }
    });

    return v;
}

销毁Fragment后更新ListView会导致应用崩溃.当Fragment被销毁时,如何使Handler停止?我还想知道如果暂停应用程序对Handler也有什么影响.

Updating the ListView after the destruction of the Fragment causes the app to crash. How can I cause the Handler to stop as the Fragment gets destroyed? I would also like to know what effects if any pausing the app has on the Handler as well.

推荐答案

您需要实现这样的处理程序

You need to implement handler like this

private Handler myHandler;
private Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        //Do Something
    }
};

@Override
public void onDestroy () {

    mHandler.removeCallbacks(myRunnable);
    super.onDestroy ();

}

这篇关于片段被销毁后停止处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆