AndroID Handler 原理分析
Handler一个让无数androID开发者头疼的东西,希望我今天这边文章能为您彻底根治这个问题
今天就为大家详细剖析下Handler的原理
Handler使用的原因
1.多线程更新Ui会导致UI界面错乱
2.如果加锁会导致性能下降
3.只在主线程去更新UI,轮询处理
Handler使用简介
其实关键方法就2个一个sendMessage,用来接收消息
另一个是handleMessage,用来处理接收到的消息
下面是我参考疯狂androID讲义,写的一个子线程和主线程之间相互通信的demo
对原demo做了一定修改
public class MainActivity extends AppCompatActivity { public final static String UPPER_NUM="upper_num"; private EditText editText; public jisuanThread jisuan; public Handler mainhandler; private TextVIEw textVIEw; class jisuanThread extends Thread{ public Handler mhandler; @OverrIDe public voID run() { Looper.prepare(); final ArrayList<Integer> al=new ArrayList<>(); mhandler=new Handler(){ @OverrIDe public voID handleMessage(Message msg) { if(msg.what==0x123){ Bundle bundle=msg.getData(); int up=bundle.getInt(UPPER_NUM); outer: for(int i=3;i<=up;i++){ for(int j=2;j<=Math.sqrt(i);j++){ if(i%j==0){ continue outer; } } al.add(i); } Message message=new Message(); message.what=0x124; Bundle bundle1=new Bundle(); bundle1.putIntegerArrayList("Result",al); message.setData(bundle1); mainhandler.sendMessage(message); } } }; Looper.loop(); } } @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); editText= (EditText) findVIEwByID(R.ID.et_num); textVIEw= (TextVIEw) findVIEwByID(R.ID.tv_show); jisuan=new jisuanThread(); jisuan.start(); mainhandler=new Handler(){ @OverrIDe public voID handleMessage(Message msg) { if(msg.what==0x124){ Bundle bundle=new Bundle(); bundle=msg.getData(); ArrayList<Integer> al=bundle.getIntegerArrayList("Result"); textVIEw.setText(al.toString()); } } }; findVIEwByID(R.ID.bt_jisuan).setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { Message message=new Message(); message.what=0x123; Bundle bundle=new Bundle(); bundle.putInt(UPPER_NUM,Integer.parseInt(editText.getText().toString())); message.setData(bundle); jisuan.mhandler.sendMessage(message); } }); } }
Hanler和Looper,MessageQueue原理分析
1.Handler发送消息处理消息(一般都是将消息发送给自己),因为hanler在不同线程是可使用的
2.Looper管理MessageQueue
Looper.loop死循环,不断从MessageQueue取消息,如果有消息就处理消息,没有消息就阻塞
public static voID loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the IDentity of this thread is that of the local process,// and keep track of what that IDentity token actually is. Binder.clearCallingIDentity(); final long IDent = Binder.clearCallingIDentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable,in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // IDentity of the thread wasn't corrupted. final long newIDent = Binder.clearCallingIDentity(); if (IDent != newIDent) { Log.wtf(TAG,"Thread IDentity changed from 0x" + Long.toHexString(IDent) + " to 0x" + Long.toHexString(newIDent) + " while dispatching to " + msg.target.getClass().getname() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }
这个是Looper.loop的源码,实质就是一个死循环,不断读取自己的MessQueue的消息
3.MessQueue一个消息队列,Handler发送的消息会添加到与自己内联的Looper的MessQueue中,受Looper管理
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
这个是Looper构造器,其中做了2个工作,
1.生成与自己关联的Message
2.绑定到当前线程
主线程在初始化的时候已经生成Looper,
其他线程如果想使用handler需要通过Looper.prepare()生成一个自己线程绑定的looper
这就是Looper.prepare()源码,其实质也是使用构造器生成一个looper
private static voID prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
4.handler发送消息会将消息保存在自己相关联的Looper的MessageQueue中,那它是如何找到这个MessageQueue的呢
public Handler(Callback callback,boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifIErs() & ModifIEr.STATIC) == 0) { Log.w(TAG,"The following Handler class should be static or leaks might occur: " + klass.getCanonicalname()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler insIDe thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
这个是Handler的构造方法,它会找到一个自己关联的一个Looper
public static Looper myLooper() { return sThreadLocal.get(); }
没错,他们之间也是通过线程关联的,得到Looper之后自然就可以获得它的MessageQueue了
5.我们再看下handler如发送消息,又是如何在发送完消息后,回调HandlerMessage的
private boolean enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg,uptimeMillis); }
这个就是Handler发送消息的最终源码,可见就是将一个message添加到MessageQueue中,那为什么发送完消息又能及时回调handleMessage方法呢
大家请看上边那个loop方法,其中的for循环里面有一句话msg.target.dispatchMessage(msg);
public voID dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
这就是这句话,看到了吧里面会调用hanlerMessage,一切都联系起来了吧
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
总结以上是内存溢出为你收集整理的Android Handler 原理分析及实例代码全部内容,希望文章能够帮你解决Android Handler 原理分析及实例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)