Android Bundle、Handler和Message類介紹

來源:互聯網
上載者:User

標籤:android   androi   intent   不同   round   str   code   strong   err   

  • Bundle是一個載體,可以存放基礎資料型別 (Elementary Data Type)、對象等內容,相當於一輛汽車,可以裝載很多東西,然後運到需要的地方,例如:

 

Bundle mBundle=new Bundle();mBundle.putString("name","zhaolinit");mBundle.putInt("number",123456);mBundle.putBoolean("flag",false);//然後,放到Intent對象中Intent mIntent=new Intent();mIntent.putExtras(mBundle);

 

 

  • Message:包含描述和任意資料對象的訊息,用於發送給Handler      

  它的成員變數如下:

public final class Message implements Parcelable {    public int what;    public int arg1;     public int arg2;    public Object obj;    ...    }

  其中what用於標識這條訊息,也可以讓接收者知道訊息是關於什麼的。arg1和arg2用於發送一些integer類型的值。obj用於傳輸任意類型的值。

 

  • Handler:訊息處理者,通過重寫Handler的handleMessage()方法,在方法中處理接收到的不同訊息,例如:
Handler mHandler=new Handler(){        @Override        public void handleMessage(Message msg) {            switch (msg.what) {                case TestHandler.TEST:
            progressValue
+= msg.arg1; Log.d("progressValue-------------->", progressValue+"");
          
break;
       }
}
}

  在其它地方,通過sendMessage()方法,發送訊息,以供handleMessage()方法接受

class myThread implements Runnable {             public void run() {                 while (!Thread.currentThread().isInterrupted()) {                                               Message message = new Message();                       message.what = TestHandler.TEST;                                             TestHandler.this.myHandler.sendMessage(message);                       try {                            Thread.sleep(100);                        } catch (InterruptedException e) {                            Thread.currentThread().interrupt();                       }                  }             }        }

        通過子線程處理一些耗時的操作,然後把處理後的結果通過sendMessage()方法發送到UI主線程。讓主線程的Handler進行UI組件的結果更新。      

Android Bundle、Handler和Message類介紹

聯繫我們

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