Android线程使用注意问题
一、众所周知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);