Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

android handler详解

$
0
0

先看演示:

一个Handler允许你发送和处理消息(Message)以及与一个线程的消息队列相关的Runnable对象。每个Handler实例都和单个线程以及该线程的消息队列有关。当你创建了一个新Handler,它就会和创建它的线程/消息队列绑定,在那以后,它就会传递消息以及runnable对象给消息队列,然后执行它们。

1为什么使用Handler

 需要使用Handler有两大主要的原因:

      (1)在将来的某个时间点调度处理消息和runnable对象;

      (2)将需要执行的操作放到其他线程之中,而不是自己的;

     调度处理消息是通过调用post(Runnable), postAtTime(Runnable, long),postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message),sendMessageAtTime(Message, long)和sendMessageDelayed(Message,long)等方法完成的。其中的post版本的方法可以让你将Runnable对象放进消息队列;sendMessage版本的方法可以让你将一个包含有bundle对象的消息对象放进消息队列,然后交由handleMessage(Message)方法处理。(这个需要你复写Handler的handleMessage方法)

    Handler在实际开发中是很常用的,主要是用来接收子线程发送的数据,然后主线程结合此数据来更新界面UI。

     Android应用程序启动时,他会开启一个主线程(也就是UI线程),管理界面中的UI控件,进行事件派发,比如说:点击一个按钮,Android会分发事件到Button上从而来响应你的操作。但是当你需要执行一个比较耗时的操作的话,例如:进行IO操作,网络通信等等,若是执行时间超过5s,那么Android会弹出一个“经典”的ANR无响应对话框,然后提示按“Force quit”或是“Wait”。解决此类问题的方法就是:我们把一些耗时的操作放到子线程中去执行。但因为子线程涉及到UI更新,而Android主线程是线程不安全的,所以更新UI的操作只能放在主线程中执行,若是放在子线程中执行的话很会出问题。所以这时就需要一种机制:主线程可以发送“命令/任务”给子线程执行,然后子线程反馈执行结果;

若在主线程中实例化一个Handler对象,例如:

     Handler mHandler = newHandler();

     此时它并没有新派生一个线程来执行此Handler,而是将此Handler附加在主线程上,故此时若你在Handler中执行耗时操作的话,还是会弹出ANR对话框!

2 例子

下面就Handler的使用举一些例子,加深理解。

2.1、post版本的Handler 

public class MainActivity extends Activity     

                implements OnClickListener {     

    private final static String TAG = "HandlerTest";     

    private final static int DELAY_TIME = 1000;     

    private Button btnStart;     

    private Button btnStop;     

    Context mContext = null;     

    /** Called when the activity is first created. */    

    @Override    

    public void onCreate(Bundle savedInstanceState) {     

        super.onCreate(savedInstanceState);     

        setContentView(R.layout.main);     

        mContext = this;     

    

        Log.i(TAG, "Main thread id = " +      

                Thread.currentThread().getId());     

        btnStart = (Button) findViewById(R.id.btn_start);     

        btnStart.setOnClickListener(this);     

        btnStop = (Button) findViewById(R.id.btn_stop);     

        btnStop.setOnClickListener(this);     

    }     

    @Override    

    public void onClick(View view) {     

        switch (view.getId()) {     

        case R.id.btn_start:     

            mHandler.postDelayed(workRunnable, DELAY_TIME);     

            break;     

        case R.id.btn_stop:     

            mHandler.removeCallbacks(workRunnable);     

            break;     

        }     

    }     

    Runnable workRunnable = new Runnable() {     

        int counter = 0;     

             

        public void run() {     

            if (counter++ < 1) {     

                Log.i(TAG, "workRunnable thread id = " +      

                        Thread.currentThread().getId());     

                mHandler.postDelayed(workRunnable, DELAY_TIME);     

            }     

        }     

    };     

    Handler mHandler = new Handler();     

}     

  

说明:发现thread id是相同的,这就说明:默认情况下创建的Handler会绑定到主线程上,你不能做太耗时的操作。

2.2 HandlerThread

  

public class MyThread2 extends Activity {     

    private Handler handler = null;     

    @Override    

    public void onCreate(Bundle savedInstanceState) {     

        super.onCreate(savedInstanceState);     

        HandlerThread handlerThread = new HandlerThread("myHandlerThread");     

        handlerThread.start();     

        handler = new Handler(handlerThread.getLooper());     

        handler.post(new MyRunnable());     

        System.out.println("Oncreate---The Thread id is :"    

                + Thread.currentThread().getId());     

        setContentView(R.layout.main);     

    }     

    private class MyRunnable implements Runnable {     

        public void run() {     

            System.out.println("Runnable---The Thread is running"); 

            System.out.println("Runnable---The Thread id is :"    

                    + Thread.currentThread().getId());     

            try {     

                Thread.sleep(6000);     

            } catch (InterruptedException e) {     

                // TODO Auto-generated catch block    

                e.printStackTrace();     

            }     

        }     

    }     

}    

  

 

在这个demo中,用到了HandlerThread,在HandlerThread对象中可以通过getLooper方法获取一个Looper对象控制句柄,我们可以将其这个Looper对象映射到一个Handler中去来实现一个线程同步机制。于是就有以下结果;

1:控制台的输出: Oncreate---The Thread id is :1

                             Runnable---The Threadis running

                             Runnable---The Threadid is :10

2:程序启动后,我们立刻看到main.xml中的内容。

这样就达到了多线程的结果

2.3 sendMessage版本的Handler

这里介绍几种模型:

2.3.1 默认的Handler

(消息处理队列挂在主线程上)

  public class MainActivity extends Activity     

                      implements OnClickListener {     

        private final static String TAG = "HandlerTest";     

        private final static int TASK_BEGIN = 1;     

        private final static int TASK_1 = 2;     

        private final static int TASK_2 = 3;     

        private final static int TASK_END   = 4;     

        private Button btnStart = null;     

        private Button btnStop = null;     

        /** Called when the activity is first created. */    

        @Override    

        public void onCreate(Bundle savedInstanceState) {     

            super.onCreate(savedInstanceState);     

            setContentView(R.layout.main);     

                 

            btnStart = (Button) findViewById(R.id.btn_start);     

            btnStart.setOnClickListener(this);     

            btnStop = (Button) findViewById(R.id.btn_stop);     

            btnStop.setOnClickListener(this);     

                 

            Log.i(TAG, "[M_TID:" + Thread.currentThread().getId() + "]");     

        }     

             

        Handler mHandler = new Handler() {     

            // 注意:在各个case后面不能做太耗时的操作,否则出现ANR对话框     

            @Override    

            public void handleMessage(Message msg) {     

                switch (msg.what) {     

                case TASK_BEGIN:     

                    Log.i(TAG, "[H_TID:" +     

                        Thread.currentThread().getId() + "] Get TASK_BEGIN");     

                    break;     

                         

                case TASK_1:     

                    Log.i(TAG, "[H_TID:" +     

                        Thread.currentThread().getId() + "] Get TASK_1");     

                    break;     

                         

                case TASK_2:     

                    Log.i(TAG, "[H_TID:" +     

                        Thread.currentThread().getId() + "] Get TASK_2");     

                    break;     

                         

                case TASK_END:     

                    Log.i(TAG, "[H_TID:" +     

                        Thread.currentThread().getId() + "] Get TASK_END");     

                    finish();     

                    break;     

                }     

                super.handleMessage(msg);     

            }     

        };     

             

        public void onClick(View view) {     

            switch (view.getId()) {     

            case R.id.btn_start:     

                // 启动任务(消息只有标识,立即投递)     

                mHandler.sendEmptyMessage(TASK_BEGIN);     

                Log.i(TAG, "Send TASK_BEGIN to handler.");     

                     

                // 开始任务1(在mHandler的消息队列中获取一个Message对象,避免重复构造)     

                Message msg1 = mHandler.obtainMessage(TASK_1);     

                msg1.obj = "This is task1";     

                mHandler.sendMessage(msg1);     

                Log.i(TAG, "Send TASK_1 to handler.");     

                     

                // 开启任务2(和上面类似)     

                Message msg2 = Message.obtain();     

                msg2.arg1 = 10;     

                msg2.arg2 = 20;     

                msg2.what = TASK_2;     

                mHandler.sendMessage(msg2);     

                Log.i(TAG, "Send TASK_2 to handler.");     

                break;     

                     

            case R.id.btn_stop:     

                // 结束任务(空消息体,延时2s投递)     

                mHandler.sendEmptyMessageDelayed(TASK_END, 2000);     

                Log.i(TAG, "Send TASK_END to handler.");     

                break;     

            }     

    }     

    }  

2.3.2消息队列仍绑定在主线程上

在子线程中发送消息。

   

 public class MainActivity extends Activity {     

        private final static String TAG = "HandlerTest";     

        private final static int TASK_BEGIN = 1;     

        private final static int TASK_1 = 2;     

        private final static int TASK_2 = 3;     

        private final static int TASK_END   = 4;     

            /** Called when the activity is first created. */    

        @Override    

        public void onCreate(Bundle savedInstanceState) {     

            super.onCreate(savedInstanceState);     

            setContentView(R.layout.main);     

                 

            Log.i(TAG, "[M_TID:" + Thread.currentThread().getId() + "]" +     

                    "This is in main thread.");     

                 

            workThread.start();     

        }     

             

        Handler mHandler = new Handler() {     

            // 注意:在各个case后面不能做太耗时的操作,否则出现ANR对话框     

            @Override    

            public void handleMessage(Message msg) {     

                switch (msg.what) {     

                case TASK_BEGIN:     

                    Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_BEGIN");     

                    break;     

                         

                case TASK_1:     

                    Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_1");     

                    break;     

                         

                case TASK_2:     

                    Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_2");     

                    break;     

                         

                case TASK_END:     

                    Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_END");     

                    finish();     

                    break;     

                }     

                super.handleMessage(msg);     

            }     

        };     

             

        Thread workThread = new Thread() {     

            // 你可以在run方法内做任何耗时的操作,然后将结果以消息形式投递到主线程的消息队列中     

            @Override    

            public void run() {     

                // 启动任务(消息只有标识,立即投递)     

                mHandler.sendEmptyMessage(TASK_BEGIN);     

                Log.i(TAG, "[S_TID:" + Thread.currentThread().getId() + "]" +     

                        "Send TASK_START to handler.");     

                     

                // 开始任务1(在mHandler的消息队列中获取一个Message对象,避免重复构造)     

                Message msg1 = mHandler.obtainMessage(TASK_1);     

                msg1.obj = "This is task1";     

                mHandler.sendMessage(msg1);     

                Log.i(TAG, "[S_TID:" + Thread.currentThread().getId() + "]" +     

                        "Send TASK_1 to handler.");     

                     

                // 开启任务2(和上面类似)     

                Message msg2 = Message.obtain();     

                msg2.arg1 = 10;     

                msg2.arg2 = 20;     

                msg2.what = TASK_2;     

                mHandler.sendMessage(msg2);     

                Log.i(TAG, "[S_TID:" + Thread.currentThread().getId() + "]" +     

                        "Send TASK_2 to handler.");     

                     

                // 结束任务(空消息体,延时2s投递)     

                mHandler.sendEmptyMessageDelayed(TASK_END, 2000);     

                Log.i(TAG, "[S_TID:" + Thread.currentThread().getId() + "]" +     

                        "Send TASK_END to handler.");     

            }     

        };     

    }    

2.3.3将消息队列绑定到子线程上,

主线程只管通过Handler往子线程的消息队列中投递消息即可。

public class MainActivity extends Activity {     

    private final static String TAG = "HandlerTest";        

    private final static int TASK_BEGIN = 1;     

    private final static int TASK_1 = 2;     

    private final static int TASK_2 = 3;     

    private final static int TASK_END   = 4;     

    private MyHandler mHandler = null;     

    /** Called when the activity is first created. */    

    @Override    

    public void onCreate(Bundle savedInstanceState) {     

        super.onCreate(savedInstanceState);     

        setContentView(R.layout.main);     

    

        Log.i(TAG, "[M_TID:" + Thread.currentThread().getId() + "]" +     

                "This is in main thread.");     

             

        HandlerThread myLooperThread = new HandlerThread("my looper thread");     

        myLooperThread.start();     

             

        Looper looper = myLooperThread.getLooper();     

        mHandler = new MyHandler(looper);     

             

        // 启动任务(消息只有标识,立即投递)     

        mHandler.sendEmptyMessage(TASK_BEGIN);     

        Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +     

                "Send TASK_START to handler.");     

             

        // 开始任务1(在mHandler的消息队列中获取一个Message对象,避免重复构造)     

        Message msg1 = mHandler.obtainMessage(TASK_1);     

        msg1.obj = "This is task1";     

        mHandler.sendMessage(msg1);     

        Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +     

                "Send TASK_1 to handler.");     

             

        // 开启任务2(和上面类似)     

        Message msg2 = Message.obtain();     

        msg2.arg1 = 10;     

        msg2.arg2 = 20;     

        msg2.what = TASK_2;     

        mHandler.sendMessage(msg2);     

        Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +     

                "Send TASK_2 to handler.");     

             

        // 结束任务(空消息体,延时2s投递)     

        mHandler.sendEmptyMessageDelayed(TASK_END, 2000);     

        Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +     

                "Send TASK_END to handler.");     

    }     

         

    class MyHandler extends Handler {     

        public MyHandler(Looper looper) {     

            super(looper);     

        }     

             

        // 现在在每个case之后,你可以做任何耗时的操作了     

        @Override    

        public void handleMessage(Message msg) {     

            switch (msg.what) {     

            case TASK_BEGIN:     

                Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_BEGIN");     

                break;     

                     

            case TASK_1:     

                Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_1");     

                break;     

                     

            case TASK_2:     

                Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_2");     

                break;     

                     

            case TASK_END:     

                Log.i(TAG, "[H_TID:" +     

                    Thread.currentThread().getId() + "] Get TASK_END");     

                finish();     

                break;     

            }     

            super.handleMessage(msg);     

        }     

    }     

}    

  

3 Demo源码

package mm.shandong.com.testhandler;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class TestHandlerActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_handler);
        textView= (TextView) findViewById(R.id.textView);
    }
    public void createSimpleHandler(View view){
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:///一般用16进制表示如0x0001
                        textView.setText(String.valueOf(msg.arg1));
                        break;
                }
            }
        };
        new Thread(){
            @Override
            public void run() {
                int i=0;
                while (i<50){
                    try {
                        Thread.sleep(100);
                        Message msg=new Message();
                        msg.what=1;
                        msg.arg1=i;
                        handler.sendMessage(msg);
                        i++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    public void createSimpleHandler2(View view){
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 0x0002:///一般用16进制表示如0x0001
                        Bundle bundle=msg.getData();
                        Map map= (Map) bundle.get("map");
                        String name= (String) map.get("name");
                        textView.setText(name);
                        break;
                }
            }
        };
        new Thread(){
            @Override
            public void run() {
                int i=0;
                while (i<50){
                    try {
                        Thread.sleep(100);
                        Message msg=new Message();
                        msg.what=0x0002;
                        Bundle bundle=new Bundle();
                        Map map=new HashMap<>();
                        map.put("name","张三"+i);
                        bundle.putSerializable("map", (Serializable) map);
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        i++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    public  void createSimpleHandler3(View view){
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:///一般用16进制表示如0x0001
                        Toast.makeText(TestHandlerActivity.this,"这是一条空消息",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        handler.sendEmptyMessage(1);
    }
    public  void createSimpleHandler4(View view){
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:///一般用16进制表示如0x0001
                        Toast.makeText(TestHandlerActivity.this,"这是延迟发送的一条空消息",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        handler.sendEmptyMessageDelayed(1,2000);
    }
    public  void createSimpleHandler5(View view){
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:///一般用16进制表示如0x0001
                        Toast.makeText(TestHandlerActivity.this,"这是通过obtainMessage从消息池中得到一条消息并发送," +
                                ""+"参数是:"+msg.arg1,Toast.LENGTH_LONG).show();
                        break;
                }
            }
        };
        Message msg=handler.obtainMessage();
        msg.what=1;
        msg.arg1=3;
        handler.sendMessage(msg);
    }
    public  void createSimpleHandler6(View view){
        MThreadNoLooper mThreadNoLooper=new MThreadNoLooper();
        mThreadNoLooper.start();
        if(mThreadNoLooper.handler!=null){
            mThreadNoLooper.handler.sendEmptyMessage(1);
        }
    }
    public  void createSimpleHandler7(View view){
        MThread mThread=new MThread();
        mThread.start();
        try {
            Thread.sleep(100);
            if(mThread.handler!=null){
                mThread.handler.sendEmptyMessage(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    public class  MThreadNoLooper extends  Thread{
        public Handler handler;
        @Override
        public void run() {
            handler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case 1:///一般用16进制表示如0x0001
                            Toast.makeText(TestHandlerActivity.this,"这是子线程中的handler监听到的消息",Toast.LENGTH_LONG).show();
                            break;
                    }
                }
            };
        }
    }
    public class  MThread extends  Thread{
        public Handler handler;
        @Override
        public void run() {
            Looper.prepare();
            handler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case 1:///一般用16进制表示如0x0001
                            Toast.makeText(TestHandlerActivity.this,"这是子线程中的handler监听到的消息",Toast.LENGTH_LONG).show();
                            break;
                    }
                }
            };
            Looper.loop();
        }
    }
}


 本人微博:honey_11

 Demo下载
最后,以上例子都来源与安卓无忧,请去应用宝或者豌豆荚下载:例子源码
,源码例子文档一网打尽。

 

作者:androidWuYou 发表于2016/9/24 10:40:29 原文链接
阅读:227 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>