Android线程——android有关线程的销毁问题

转自http://blog.chinaunix.net/uid-23392298-id-3397240.html

众所周知Hanlder是线程与Activity通信的桥梁,我们在开发好多应用中会用到线程,有些人处理不当,会导致当程序结束时,线程并没有被销毁,而是一直在后台运行着,当我们重新启动应用时,又会重新启动一个线程,周而复始,你启动应用次数越多,开启的线程数就越多,你的机器就会变得越慢。这时候就需要在destory()方法中对线程进行一下处理!

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();
    } 
}
//将线程销毁,否则返回activity,但是线程会一直在执行,log里面的信息会增加,会消耗过多的内存!
  
mHandler.removeCallbacks(mRunnable);


你可能感兴趣的:(android线程)