Android線程通訊

來源:互聯網
上載者:User

標籤:android   des   style   blog   http   color   

摘要

  andriod提供了 Handler 和 Looper 來滿足線程間的通訊。例如一個子線程從網路上下載了一副圖片,當它下載完成後會發送訊息給主線程,這個訊息是通過綁定在主線程的Handler來傳遞的。

 

本文

圖解:

程式碼範例:

/** * @author allin.dev *         http://allin.cnblogs.com */public class MainThread extends Activity{    private static final String TAG = "MainThread";  private Handler mMainHandler, mChildHandler;  private TextView info;  private Button msgBtn;    @Override  public void onCreate( Bundle savedInstanceState )  {    super.onCreate( savedInstanceState );    setContentView( R.layout.main );        info = (TextView) findViewById( R.id.info );    msgBtn = (Button) findViewById( R.id.msgBtn );        mMainHandler = new Handler( )    {            @Override      public void handleMessage( Message msg )      {        Log.i( TAG, "Got an incoming message from the child thread - "            + (String) msg.obj );        // 接收子線程的訊息        info.setText( (String) msg.obj );      }          };        new ChildThread( ).start( );        msgBtn.setOnClickListener( new OnClickListener( )    {            @Override      public void onClick( View v )      {                if ( mChildHandler != null )        {                    // 發送訊息給子線程          Message childMsg = mChildHandler.obtainMessage( );          childMsg.obj = mMainHandler.getLooper( ).getThread( ).getName( )              + " says Hello";          mChildHandler.sendMessage( childMsg );                    Log.i( TAG, "Send a message to the child thread - "              + (String) childMsg.obj );                  }      }    } );      }    public void onDestroy() {      super.onDestroy();    Log.i(TAG, "Stop looping the child thread‘s message queue");    mChildHandler.getLooper().quit();  }    class ChildThread extends Thread  {        private static final String CHILD_TAG = "ChildThread";        public void run( )    {      this.setName( "ChildThread" );            // 初始化訊息迴圈隊列,需要在Handler建立之前      Looper.prepare( );            mChildHandler = new Handler( )      {        @Override        public void handleMessage( Message msg )        {          Log.i( CHILD_TAG, "Got an incoming message from the main thread - "              + (String) msg.obj );                    try          {                        // 在子線程中可以做一些耗時的工作            sleep( 100 );                        Message toMain = mMainHandler.obtainMessage( );            toMain.obj = "This is " + this.getLooper( ).getThread( ).getName( )                + ".  Did you send me \"" + (String) msg.obj + "\"?";                        mMainHandler.sendMessage( toMain );                        Log.i( CHILD_TAG, "Send a message to the main thread - "                + (String) toMain.obj );                      }          catch ( InterruptedException e )          {            // TODO Auto-generated catch block            e.printStackTrace( );          }        }              };            Log.i( CHILD_TAG, "Child handler is bound to - "          + mChildHandler.getLooper( ).getThread( ).getName( ) );            // 啟動子線程訊息迴圈隊列      Looper.loop( );    }  }}

 ps:

使用HandlerThread的looper對象建立Handler,如果使用預設的構造方法,很有可能阻塞UI線程,參考http://www.cnblogs.com/ccdc/p/3837798.html。改進方案新開一個線程將主線程的handler使用新開線程的looper替代主線程looper,如下,

 

參考

shangdawei.android 線程間通訊[2014-07-11](2013-03-26).http://www.cnblogs.com/shangdawei/archive/2013/03/26/2983217.html

 

 

聯繫我們

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