亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

android使用handlerthread創(chuàng)建線程示例

 更新時(shí)間:2014年01月11日 15:32:28   作者:  
這篇文章主要介紹了android使用handlerthread創(chuàng)建線程,講解了這種方式的好處及為什么不使用Thread類的原因

在android開發(fā)中,一說起線程的使用,很多人馬上想到new Thread(){...}.start()這種方式。
這樣使用當(dāng)然可以,但是多次使用這種方式,會(huì)創(chuàng)建多個(gè)匿名線程。使得程序運(yùn)行起來越來越慢。
因此,可以考慮使用一個(gè)Handler來啟動(dòng)一個(gè)線程,當(dāng)該線程不再使用就刪除,保證線程不會(huì)重復(fù)創(chuàng)建。
一般會(huì)使用Handler handler = new Handler(){...}創(chuàng)建Handler。這樣創(chuàng)建的handler是在主線程即UI線程下的Handler,
即這個(gè)Handler是與UI線程下的默認(rèn)Looper綁定的。Looper是用于實(shí)現(xiàn)消息隊(duì)列和消息循環(huán)機(jī)制的。
因此,如果是默認(rèn)創(chuàng)建Handler那么如果線程是做一些耗時(shí)操作如網(wǎng)絡(luò)獲取數(shù)據(jù)等操作,這樣創(chuàng)建Handler是不行的。
Android API提供了HandlerThread來創(chuàng)建線程。官網(wǎng)的解釋是:Handy class for starting a new thread that has a looper.
The looper can then be used to create handler classes. Note that start() must still be called.
HandlerThread實(shí)際上就一個(gè)Thread,只不過它比普通的Thread多了一個(gè)Looper。
創(chuàng)建HandlerThread時(shí)要把它啟動(dòng)了,即調(diào)用start()方法。然后創(chuàng)建Handler時(shí)將HandlerThread中的looper對(duì)象傳入。

復(fù)制代碼 代碼如下:

HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
mHandler = new Handler(thread.getLooper());
mHandler.post(new Runnable(){...});

那么這個(gè)Handler對(duì)象就是與HandlerThread這個(gè)線程綁定了(這時(shí)就不再是與UI線程綁定了,這樣它處理耗時(shí)操作將不會(huì)阻塞UI)。 下面是代碼說明:

復(fù)制代碼 代碼如下:

public class MainActivity extends Activity implements OnClickListener{
private Handler mHandler;
private HandlerThread mHandlerThread;

private boolean mRunning;

private Button btn;

@Override
protected void onDestroy() {
    mRunning = false;
    mHandler.removeCallbacks(mRunnable);
    super.onDestroy();
}

@Override
protected void onResume() {
    mRunning = true;
    super.onResume();
}

@Override
protected void onStop() {
    mRunning = false;
    super.onStop();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(this);

    mHandlerThread = new HandlerThread("Test", 5);
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());
}

private Runnable mRunnable = new Runnable() {

    @Override
    public void run() {
        while (mRunning) {
            Log.d("MainActivity", "test HandlerThread...");
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
};

@Override
public void onClick(View v) {
    switch(v.getId()) {
    case R.id.btn :
        mHandler.post(mRunnable);
        break;
    default :
        break;
    }

}
}

相關(guān)文章

最新評(píng)論