注: 相关图片都是用的别人的
1.Handler 主要用于消息处理
2.Message:消息,子线程向UI线程发送消息,消息中携带者相应数据。
3.MessageQueue:消息队列,有一个格Message消息组成
4.Looper :信息泵,循环处理消息队列MessageQueue中的Message,将其发送给相应的Handler
5.带Looper的Thread,如果要非UI线程中实例化Handler,必须有Looper,而一般子线程中是不存在Looper的,一个线程可以有一个Looper对象和一个MessageQueue,必行显示调用Looper.loop( )方法给其分配出Looper对象才能使用。
一个线程对应一个Looper。
一个Looper对应一个MessageQueue。
一个Looper可以对应多个Handler。
记住:HandlerThread =普通Thread+Looper
详细的运行过程看下两图:
一.Handler的方法使用
Handler可以将两种类型消息放到消息队列中,一种是Message另种是Runnable对象,如果是Message对象时,通过Handler的handleMessage( )方法处理,如果是Runnable对象的时候,当Handler拿到Looper发送过来的Runnable对象的时候,会直接运行Runnable的run( )方法,注意Runnable对象时运行在相应Handler所在的线程中的(一般是UI线程),没有start,直接调用了run( )方法。
/** * * handler.post(Runnable); * * */ handler.post(new Runnable() { @Override public void run() { isChanging = true; bar.setProgress(count); count++; } }); /** * * * hanlder.postDelayer(Runnable,timeDelayed); * */ handler.postDelayed(new Runnable() { @Override public void run() { isChanging = true; bar.setProgress(count); count++; } },100); /** * 重点看一下handler是怎么发送msg的 * * 1.可以发送空的Message * 2.可以定时发送Message * 3.Message可以携带的数据有 int what,int arg1,int arg2,Object obj, Bundle bundler(通过msg.setData(Bundle bundler)来添加到Message对象中) * * 4.Message通过Handler.obtain()方法实例化,可以进行有参、无参实例化,其中有参实例化是可以出传入 int what,int arg1,int arg2, Object obj * @author VicentTung * */ /** * 1.发送空的Message */ handler.sendEmptyMessage(0); handler.sendEmptyMessageAtTime(0, System.currentTimeMillis()); handler.sendEmptyMessageDelayed(0, 100); /** *2. 发送非空Message(Message是new出来的) */ Message msg =new Message(); Bundle data_bundle = new Bundle(); data_bundle.putString("name", "小明"); data_bundle.putInt("age", 12); msg.arg1=1; msg.arg2=2; msg.what=3; msg.obj="success"; msg.setData(data_bundle); handler.sendMessageDelayed(msg, 100); /** * 3.发送非空Message(Message是handler.obtain()出来的) */ String obj="hahah"; int arg1=111; int arg2=222; Message msg_obtain =handler.obtainMessage(); /** * 各种各样的带参数的obtain()方法实例化出Message对象 */ msg_obtain =handler.obtainMessage(what); msg_obtain = handler.obtainMessage(what, obj); msg_obtain = handler.obtainMessage(what, arg1, arg2); msg_obtain =handler.obtainMessage(what, arg1, arg2, obj); /** * 4.Message的移除 */ if(handler.hasMessages(0)){ handler.removeMessages(0); }
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。