一、衆所周知Hanlder是線程與Activity通信的橋樑,我們在開發好多應用中會用到線程,有些人處理不當,會導致當程序結束時,線程並沒有被銷燬,而是一直在後臺運行着,當我們重新啓動應用時,又會重新啓動一個線程,周而復始,你啓動應用次數越多,開啓的線程數就越多,你的機器就會變得越慢。這時候就需要在destory()方法中對線程進行一下處理!
二、main。xml佈局文件
<?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 原創" /> </LinearLayout>
三、Threademo類
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); //每兩秒重啓一下線程 mHandler.postDelayed(mRunnable, 2000); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView)findViewById(R.id.textview01); //通過handler啓動線程 mHandler.post(mRunnable); } @Override protected void onDestroy() { mHandler.removeCallbacks(mRunnable); super.onDestroy(); } }
四、特別注意onDestroy()方法中的代碼
//將線程銷燬,否則返回activity,但是線程會一直在執行,log裏面的信息會增加,會消耗過多的內存!
mHandler.removeCallbacks(mRunnable);