Android入門:Handler簡介與執行個體

來源:互聯網
上載者:User

標籤:

轉自:http://www.bdqn.cn/news/201303/8038.shtml

1、Handler簡介

Handler 為Android作業系統中的線程通訊工具,包為android.os.Handler。

與Handler綁定的有兩個隊列,一個為訊息佇列,另一個為線程隊列。Handler可以通過這兩個隊列來分別:

發送、接受、處理訊息–訊息佇列;

啟動、結束、休眠線程–線程隊列;

Android OS中,一個進程被建立之後,主線程(可理解為當前Activity)建立一個訊息佇列,這個訊息佇列維護所有頂層應用對象(Activities, Broadcast receivers等)以及主線程建立的視窗。你可以在主線程中建立新的線程,這些新的線程都通過Handler與主線程進行通訊。通訊通過新線程調用Handler的post()方法和sendMessage()方法實現,分別對應功能:

post() 將一個線程加入線程隊列;

sendMessage() 發送一個訊息對象到訊息佇列;

當然,post()方法還有一些變體,比如postDelayed()、postAtTime()分別用來延遲發送、定時發送;

訊息的處理,在主線程的Handler對象中進行;具體處理過程,需要在new Handler對象時使用匿名內部類重寫Handler的handleMessage(Message msg)方法;

從訊息佇列中擷取訊息。

線程加入線程隊列可以在主線程中也可以在子線程中進行,但都要通過主線程的Handler對象調用post()。

2、Handler執行個體

與ProgressBar結合的例子:

 

package mars.barhandler;        import android.app.Activity;    import android.os.Bundle;    import android.os.Handler;    import android.os.Message;    import android.view.View;    import android.view.View.OnClickListener;    import android.widget.Button;    import android.widget.ProgressBar;        public class TestBarHandler extends Activity {            /** Called when the activity is first created. */            //聲明控制項變數            ProgressBar bar = null;            Button startButton = null;            @Override            public void onCreate(Bundle savedInstanceState) {                    super.onCreate(savedInstanceState);                    setContentView(R.layout.main);                    //根據控制項的ID得到代表控制項的對象,並為按鈕設定監聽器                    bar = (ProgressBar)findViewById(R.id.bar);                    startButton = (Button)findViewById(R.id.startButton);                    startButton.setOnClickListener(new ButtonListener());            }            //當點擊startButton按鈕時,就會執行ButtonListener的onClick方法            class ButtonListener implements OnClickListener{                        public void onClick(View v) {                            // TODO Auto-generated method stub                            bar.setVisibility(View.VISIBLE);                            updateBarHandler.post(updateThread);                    }                                }            //使用匿名內部類來複寫Handler當中的handleMessage方法            Handler updateBarHandler = new Handler(){                        @Override                    public void handleMessage(Message msg) {                            bar.setProgress(msg.arg1);                            Bundle bundle = msg.getData();                            updateBarHandler.post(updateThread);                            System.out.println("test---->" + bundle.getString("test"));                    }                                };            //線程類,該類使用匿名內部類的方式進行聲明            Runnable updateThread = new Runnable(){                    int i = 0 ;                    public void run() {                            System.out.println("Begin Thread" + i);                            i = i + 10 ;                            //得到一個訊息對象,Message類是有Android作業系統提供                            Message msg = updateBarHandler.obtainMessage();                                                        //將msg對象的arg1參數的值設定為i,用arg1和arg2這兩個成員變數傳遞訊息,優點是系統效能消耗較少                            msg.arg1 = i ;                            Bundle bundle = new Bundle();                            bundle.putString("test", "test bundle");                            msg.setData(bundle);                            try {                                    //設定當前顯示睡眠1秒                                    Thread.sleep(1000);                            } catch (InterruptedException e) {                                    // TODO Auto-generated catch block                                    e.printStackTrace();                            }                            //將msg對象加入到訊息佇列當中                            if( i > 100){                                    //如果當i的值為100時,就將線程對象從handler當中移除                                    updateBarHandler.removeCallbacks(updateThread);                                    System.out.println(">>>>>>");                            }else{                                    updateBarHandler.sendMessage(msg);                                    System.out.println("<<<<<<");                            }                    }            };            class MyThread extends Thread{                    public void run(){                                                }            }                }

  

 

Android入門:Handler簡介與執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.