I. As we all know, hanlder is a bridge between threads and activities. We will use threads in many applications. Some users may improperly process the threads. When the program ends, the threads will not be destroyed, it is always running in the background. When we restart the application, a thread will be restarted. The more times you start the application, the more threads you open, your machine will become slower. At this time, we need to process the thread in the destory () method!
Ii. Main. XML layout File
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <textview Android: id = "@ + ID/textview01" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "Daming original"/> </linearlayout>
Iii. threademo class
Package com.cn. android; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. util. log; import android. widget. textview; public class threaddemo extends activity {/** called when the activity is first created. */Private Static final string tag = "threaddemo"; private int COUNT = 0; private handler mhandler = new handler (); Private textview mtextview = NULL; private runnable mrunnable = new runnable () {@ override public void run () {// todo auto-generated method stub log. E (TAG, thread. currentthread (). getname () + "" + count); count ++; mtextview. settext ("" + count); // restart the mhandler thread every two seconds. postdelayed (mrunnable, 2000) ;};@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); mtextview = (textview) findviewbyid (R. id. textview01); // start the mhandler thread through handler. post (mrunnable) ;}@ override protected void ondestroy () {mhandler. removecallbacks (mrunnable); super. ondestroy ();}}
4. Pay special attention to the Code in the ondestroy () method
// Destroy the thread. Otherwise, the activity is returned, but the thread will be executed all the time. The information in the log will increase, which will consume too much memory!
Mhandler. removecallbacks (mrunnable );