android線程使用注意問題?【安卓進化二】

來源:互聯網
上載者:User

一、眾所周知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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.