1. handler 1.1 概述 处理对象:handler是用来发送、处理线程中MessageQueue里的消息或者Runnable的对象; 实例特点:一个handler的实例对应于一个线程和该线程的 MessageQueue; 自动绑定:当handler被创建之后,它就自动和创建它的线程和MessageQueue绑定在一起; 1.2 用途 延时处理:将消息或者Runnables放在将来的某个时间点去执行; 多线程间:将排队等候执行的操作放到其它的线程里面去执行。 1.3 说明 时间延迟:我们知道handler处理的操作都是放在一个queue里面的,因此当我们post一个runnable(post(Runnable r))之后,要想很快执行后面的操作则需要等待;
sample:
public class MainAcitivty extends Activity { private final static int CMD_MSG = 0; private final static String TAG = "TAG"; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case CMD_MSG: Android.util.Log.d(TAG, "CMD_MSG"); break; } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sendMessage(); } private void sendMessage() { mHandler.post(new Runnable() { @Override public void run() { SystemClock.sleep(5000); } }); mHandler.obtainMessage(CMD_MSG).sendToTarget(); } }
handler数量:一个handler一定对应一个线程,反过来在一个线程里面却可以创建多个handler;sample:
public class MainAcitivty extends Activity { private final static int CMD_MSG = 0; private final static String TAG = "TAG"; private final Handler mHandler1 = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case CMD_MSG: android.util.Log.d(TAG, "CMD_MSG"); break; } } }; private final Handler mHandler2 = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case CMD_MSG: android.util.Log.d(TAG, "CMD_MSG"); break; } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sendMessage(); } private void sendMessage() { mHandler1.obtainMessage(CMD_MSG).sendToTarget(); mHandler2.obtainMessage(CMD_MSG).sendToTarget(); }