Android experts should pay attention to the use of runable, androidrunable
Read a piece of code:
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() {@Overridepublic void run() { Log.e(TAG, Thread.currentThread().getName() + " " +count); ++count; setTitle("" +count); //Performed once every two seconds mHandler.postDelayed(mRunnable, 2000); }};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_thread_demo); mHandler.post(mRunnable); }}
Then, press the return key to exit.
Come in again. Problems found:
That is to say, in addition to the runable that was previously run, there is another
In the ondrestroy method, add
MHandler. removeCallbacks (mRunnable );
@Overrideprotected void onDestroy() {mHandler.removeCallbacks(mRunnable);super.onDestroy();}