zoukankan      html  css  js  c++  java
  • android の Handler消息传递机制

    Handler类的主要作用有两个:

    ==》在新启动的线程中发送消息。

    ==》在主线程中获取、处理消息。

    View Code
    public class TestActivity extends Activity {
        
        private Button btnStart,btnEnd;
        private ProgressBar proBar;
        
        protected void init(){
            btnStart = (Button)findViewById(R.id.start);
            btnEnd = (Button)findViewById(R.id.end);
            proBar = (ProgressBar)findViewById(R.id.pBar);
        }
        
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            btnStart.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    proBar.setVisibility(View.VISIBLE);
                    //1.将一个线程加入线程队列;
                    updateBarHandler.post(updateBarThread);
                }
            });
    
            btnEnd.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    updateBarHandler.removeCallbacks(updateBarThread);
                }
            });
        }
        
         Handler updateBarHandler = new Handler(){
            public void handleMessage(Message msg) {
                //3.主线程中获取处理消息
                proBar.setProgress(msg.arg1);
                updateBarHandler.post(updateBarThread);
            }
            
        };
        
        Runnable updateBarThread = new Runnable() {
            int i = 0;
            public void run() {
                i = i + 10;
                Message msg = updateBarHandler.obtainMessage();
                msg.arg1 = i;
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //2.新线程中发送一个消息到消息队列
                updateBarHandler.sendMessage(msg);
                if(i == 100){
                    updateBarHandler.removeCallbacks(updateBarThread);
                }
            }
        };
    }

    这里有两种队列,

    一种是线程队列,就是用postXX方法或者removeCallbacks方法对线程对象的操作。

    一种是消息队列,用sendMessage和handleMessage方法来对消息对象进行处理。

  • 相关阅读:
    手指抽搐强迫症 之 APM病理分析器 v0.0.0.3 (11月24日更新)
    [转帖]修改MySql密码及访问限制设置详解
    C#学习笔记
    CodeSmith快速向导
    奇葩的maxscript
    MASM中可以定义的变量类型
    js琐记
    史上最全的css hack(ie69,firefox,chrome,opera,safari)
    逆向win32程序的思路琐记
    makefile伪目标
  • 原文地址:https://www.cnblogs.com/zyoohoo/p/2513809.html
Copyright © 2011-2022 走看看