简体   繁体   English

如何通过Messenger类将延迟的消息发送到另一个进程

[英]how to send delayed message to another process via Messenger class

I am learning Android Service from http://developer.android.com/guide/components/bound-services.html , but after practicing by writing some sample code, I start to have following questions: 我正在从http://developer.android.com/guide/components/bound-services.html学习Android服务,但是在通过编写一些示例代码进行练习之后,我开始遇到以下问题:

First, I would like to know how do we send delayed msg by Messenger class in Android. 首先,我想知道如何通过Android中的Messenger类发送延迟的味精。

Second, why don't we have methods like sendDelayedMsg() or sendMsgAt() in Messenger class ? 其次,为什么Messenger类中没有像sendDelayedMsg()或sendMsgAt()这样的方法?

Thank you~ 谢谢〜

I'll answer your 2nd question first and your 1st question second, since that's probably the more logical way to explain this. 我将首先回答您的第二个问题,然后回答您的第一个问题,因为这可能是更合理的解释方式。

Messenger is a wrapper around a binder which is used for interprocess communication. Messenger是围绕活页夹的包装,用于进程间通信。 As such, you don't have direct access to a Handler of a thread on the target process. 因此,您无法直接访问目标进程上的线程的处理程序。 So, you can't do something like Handler.postDelayed() or Handler.postAtTime() which you seem to be alluding to with your sendDelayedMsg() and sendMsgAt(). 因此,您无法执行类似于Handler.postDelayed()或Handler.postAtTime()之类的事情,这些事情似乎与您的sendDelayedMsg()和sendMsgAt()有关。

Now, as to your 1st question: You can implement a "send delayed msg" using Messenger as follows: 现在,关于您的第一个问题:您可以使用Messenger实施“发送延迟的消息”,如下所示:

  1. In your service class (which is run by your target process), create a Handler object for receiving messages from the Messenger. 在服务类(由目标进程运行)中,创建一个Handler对象以接收来自Messenger的消息。 Your Handler object should extend the Handler class and in which you implement the "handleMessage(Message msg)". 您的Handler对象应扩展Handler类,并在其中实现“ handleMessage(Message msg)”。

  2. Your "handleMessage(Message msg)" method receives messages from the Messengers. 您的“ handleMessage(Message msg)”方法接收来自Messenger的消息。 So, for each type of message (ie, Message.what) that you want to delay, post it to your Handler object by calling postDelayed() or postAtTime(). 因此,对于要延迟的每种消息(即Message.what),请通过调用postDelayed()或postAtTime()将其发布到Handler对象。 In other words, when your target process/service receives a message that you want to delay, it schedules that a delay for that message. 换句话说,当您的目标进程/服务收到您要延迟的消息时,它计划对该消息进行延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM