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

时间:2018-06-11 14:18:21

标签: java android

我在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);
                }
            }
        };

现在杀死这个的最好方法是什么?我应该像在这里一样使用某些内容:handler.removeCallbacksAndMessages(null);onStop()onDestroy()中进行操作会更好吗?

1 个答案:

答案 0 :(得分:0)

你无法阻止Runnable。你可以停止接收这样的回调。

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);