简体   繁体   English

从服务到活动的Android广播

[英]Android Broadcast from Service To Activity

I am trying to send a Broadcast from a service out to an Activity. 我正在尝试从服务发送广播到活动。 I can verify the broadcast is sent from within the service, but the Activity doesn't pick up anything. 我可以验证广播是从服务中发送的,但是活动不会发送任何内容。

Here is the relevant service code: 这是相关的服务代码:

   Intent i = new Intent(NEW_MESSAGE);  
   i.putExtra(FriendInfo.USERNAME, StringUtils.parseBareAddress(message.getFrom()));
   i.putExtra(FriendInfo.MESSAGE, message.getBody());
   i.putExtra("who", "1");
   sendBroadcast(i);

And the receiving end in the activity class: 并且活动类中的接收端:

public class newMessage extends BroadcastReceiver 
{
@Override
   public void onReceive(Context context, Intent intent) 
   {    
    String action = intent.getAction();
       if(action.equalsIgnoreCase(IMService.NEW_MESSAGE)){    
          Bundle extra = intent.getExtras();
          String username = extra.getString(FriendInfo.USERNAME);   
          String message = extra.getString(FriendInfo.MESSAGE);
          String who = extra.getString("who");
         }
   }
}

The BroadcastReceiver is defined within an Activity. BroadcastReceiver在Activity中定义。 I am registering the receiver in the onCreate method of the Activity, not in the Manifest file. 我在Activity的onCreate方法中注册接收器,而不是在Manifest文件中。

I'm stumped as to why it won't rec. 我很难过为什么它不会记录。 anything. 任何东西。

Any insight? 任何见解?

EDIT 编辑
Registering takes place as follows: 注册如下:

 registerReceiver(messageReceiver, new IntentFilter(IMService.NEW_MESSAGE));

Where "messageReceiver" is defined as 其中“messageReceiver”定义为

private newMessage messageReceiver = new newMessage();

IMService.NEW_MESSAGE is merely a string = "NewMessage" IMService.NEW_MESSAGE只是一个string =“NewMessage”

我不确定它是否特定于设置,或者它是否一般是修复,但是将register/unregister移动到onResume/onPause _respectively_并且没有在onCreate注册解决了我的问题。

Try this two things: 试试这两件事:

  1. Use manifest file to register receiver(but it barely helps) 使用清单文件注册接收器(但它几乎没有帮助)
  2. Try make your Receiver a regular class, not inner one. 尝试让您的Receiver成为常规课程,而不是内部课程。

Inner class broadcast receiver will not be able to handle broadcast(means it unable to locate that class ). 内部类广播接收器将无法处理广播(意味着它无法定位该类)。 So make it as a separate class 所以把它作为一个单独的类

Definitely it will work. 绝对会起作用。

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

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