在Activity开启的子线程并不会自动随Activity的destroy而关闭,所以必须手动去关闭子线程或者通过boolean的方式让子线程结束运行。开启的子线程有for循环的要更加注意。
1 package com.lsw; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Handler; 6 import android.os.Message; 7 import android.util.Log; 8 public class ThreadDemoActivity extends Activity { 9 private static final String TAG = "ThreadDemo"; 10 private int count = 0; 11 private Handler mHandler = new MyHandler(); 12 boolean stopThread=false; 13 14 private Runnable mRunnable = new Runnable() { 15 16 public void run() { 17 18 while (!stopThread) 19 { 20 count++; 21 try 22 { 23 Thread.sleep(2000); 24 } 25 catch (InterruptedException e) 26 { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 31 //虽然Message的构造函数是public的,但是最好是使用Message.obtain( )或Handler.obtainMessage( )函数来获取Message对象,因为Message的实现中包含了回收再利用的机制,可以提供效率。 32 Message message=mHandler.obtainMessage(); 33 message.what=0; 34 message.obj=count; 35 mHandler.sendMessage(message); 36 } 37 } 38 }; 39 40 @Override 41 public void onCreate(Bundle savedInstanceState) { 42 super.onCreate(savedInstanceState); 43 setContentView(R.layout.main); 44 //开启子线程 45 new Thread(mRunnable).start(); 46 } 47 48 protected void onDestroy() { 49 System.out.println("-----------onDestroy------"); 50 stopThread=true; 51 super.onDestroy(); 52 }; 53 54 class MyHandler extends Handler{ 55 56 @Override 57 public void handleMessage(Message msg) 58 { 59 // TODO Auto-generated method stub 60 Log.e(TAG, Thread.currentThread().getName() + " " +msg.obj); 61 setTitle("" +msg.obj); 62 } 63 } 64 65 }