zoukankan      html  css  js  c++  java
  • Android Bundle、Handler和Message类介绍

    • Bundle是一个载体,可以存放基本数据类型、对象等内容,相当于一辆汽车,可以装载很多东西,然后运到需要的地方,例如:
    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组件的结果更新。

          

     程序猿必读

  • 相关阅读:
    bzoj 3339 莫队
    E. XOR and Favorite Number
    HDU 2222 AC自动机
    SPOJ 694 不同子串个数
    Codeforces Round #428 (Div. 2)
    HDU 6103
    《贪婪的动态规划》
    《浅谈图论模型的建立与应用》
    bzoj 2194 快速傅里叶之二
    java中高级面试题整理及参考答案
  • 原文地址:https://www.cnblogs.com/longzhongren/p/6102594.html
Copyright © 2011-2022 走看看