Android应用程序如何把消息加入到消息队列中

这篇文章主要介绍“Android应用程序如何把消息加入到消息队列中”,在日常操作中,相信很多人在Android应用程序如何把消息加入到消息队列中问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Android应用程序如何把消息加入到消息队列中”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

应用程序的主线程准备就好消息队列并且进入到消息循环后,其它地方就可以往这个消息队列中发送消息了。

在Android应用程序启动过程源代码分析这篇文章的Step  30中,ActivityManagerService通过调用ApplicationThread类的scheduleLaunchActivity函 数通知应用程序。

它可以加载应用程序的默认Activity了,这个函数定义在frameworks/base/core/java/android /app/ActivityThread.java文件中:

[java] view plaincopypublic final class ActivityThread { ...... private final class ApplicationThread extends ApplicationThreadNative { ...... // we use token to identify this activity without having to send the // activity itself back to the activity manager. (matters more with ipc) public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Bundle state, List pendingResults, List pendingNewIntents, boolean notResumed, boolean isForward) { ActivityClientRecord r = new ActivityClientRecord(); r.token = token; r.ident = ident; r.intent = intent; r.activityInfo = info; r.state = state; r.pendingResults = pendingResults; r.pendingIntents = pendingNewIntents; r.startsNotResumed = notResumed; r.isForward = isForward; queueOrSendMessage(H.LAUNCH_ACTIVITY, r); } ...... } ...... }

这里把相关的参数都封装成一个ActivityClientRecord对象r,然后调用queueOrSendMessage函数来往应用程序的消息队 列中加入一个新的消息(H.LAUNCH_ACTIVITY),这个函数定义在frameworks/base/core/java/android /app/ActivityThread.java文件中:

[java] view plaincopypublic final class ActivityThread { ...... private final class ApplicationThread extends ApplicationThreadNative { ...... // if the thread hasn't started yet, we don't have the handler, so just // save the messages until we're ready. private final void queueOrSendMessage(int what, Object obj) { queueOrSendMessage(what, obj, 0, 0); } ...... private final void queueOrSendMessage(int what, Object obj, int arg1, int g2) { synchronized (this) { ...... Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; mH.sendMessage(msg); } } ...... } ...... }

到此,关于“Android应用程序如何把消息加入到消息队列中”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!