问题描述
所以,我理解(我认为)关于广播意图和接收消息给他们。
So I understand (I think) about broadcast intents and receiving messages to them.
所以,现在,我的问题/我可以不知道是如何发送从接收的的onReceive
方法的消息的活动。可以说我有一个接收器,这样的:
So now, my problem/what I can't work out is how to send a message from the onReceive
method of a receiver to an activity. Lets say I have a receiver as such:
public class ReceiveMessages extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action.equalsIgnoreCase(TheService.DOWNLOADED)){
// send message to activity
}
}
}
我将如何将消息发送到活动?
How would I send a message to an activity?
我本来实例中我想发送消息到并以某种方式监视它的活动的接收器?或者是什么?我理解这个概念,但没有真正的应用程序。
Would I have to instantiate the receiver in the activity I want to send messages to and monitor it somehow? Or what? I understand the concept, but not really the application.
任何帮助将是绝对惊人的,谢谢你。
Any help would be absolutely amazing, thank you.
汤姆
推荐答案
EDITED 修正code用于注册/注销例子的BroadcastReceiver
并且还去掉舱单申报。
EDITED Corrected code examples for registering/unregistering the BroadcastReceiver
and also removed manifest declaration.
定义 ReceiveMessages
为活动
,需要监听从<$ C $消息中的一个内部类C>服务。
然后,声明类变量,如...
Then, declare class variables such as...
ReceiveMessages myReceiver = null;
Boolean myReceiverIsRegistered = false;
在的onCreate()
使用 myReceiver =新ReceiveMessages();
然后在 onResume()
...
if (!myReceiverIsRegistered) {
registerReceiver(myReceiver, new IntentFilter("com.mycompany.myapp.SOME_MESSAGE"));
myReceiverIsRegistered = true;
}
...在的onPause()
...
if (myReceiverIsRegistered) {
unregisterReceiver(myReceiver);
myReceiverIsRegistered = false;
}
在服务
创建和播放意图
...
In the Service
create and broadcast the Intent
...
Intent i = new Intent("com.mycompany.myapp.SOME_MESSAGE");
sendBroadcast(i);
和仅此而已。使行动唯一的你的包/应用程序,例如, com.mycompany ...
在我的例子。这有助于避免出现在其他应用程序或系统组件可能会尝试对其进行处理。
And that's about it. Make the 'action' unique to your package / app, i.e., com.mycompany...
as in my example. This helps avoiding a situation where other apps or system components might attempt to process it.
这篇关于使用广播的意图/广播接收到从服务将消息发送到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!