看一段代码:
package com.example.threaddemo; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.util.Log; import android.view.Menu; public class ThreadDemo extends Activity { private static final String TAG = "ThreadDemo"; private int count = 0; private Handler mHandler = new Handler(); private Runnable mRunnable = new Runnable() { @Override public void run() { Log.e(TAG, Thread.currentThread().getName() + " " +count); ++count; setTitle("" +count); //Performed once every two seconds mHandler.postDelayed(mRunnable, 2000); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_demo); mHandler.post(mRunnable); } }
然后我们按返回键退出。
再进来。发现问题:
就是说,除了之前运行的runable,又多了一个
如何解决,在ondrestroy方法中添加
mHandler.removeCallbacks(mRunnable);
@Override protected void onDestroy() { mHandler.removeCallbacks(mRunnable); super.onDestroy(); }
时间: 2024-11-05 11:37:06