简体   繁体   English

如何安全地停止处理程序?

[英]How to safely stop a handler?

I have a handler in android defined as this : 我在android中定义了以下处理程序:

myHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg){

                switch (msg.what){

                    case 1:

                        break;

                    case 5:

                        break;

                    case 4:

                        break;
                    case 3:

                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        };

Now what is the best way to kill clear this ? 现在,消除这种情况的最佳方法是什么? Should I use something as they do here: handler.removeCallbacksAndMessages(null); 我是否应该像在这里一样使用它们: handler.removeCallbacksAndMessages(null); Is it better to do in in onStop() or onDestroy() ? 最好在onStop()onDestroy()吗?

You can not stop a Runnable. 您无法停止Runnable。 You can just stop receiving Callbacks like this. 您可以停止接收这样的回调。

Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Intent i = new
                Intent(MapsActivity.this,MapsActivity.class);
        startActivity(i);
        finish();
    }
};
handler.post(runnable);

// use this when you don't want callback to be called anymore
handler.removeCallbacks(runnable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM