简体   繁体   中英

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. I am registering the receiver in the onCreate method of the Activity, not in the Manifest file.

I'm stumped as to why it won't rec. anything.

Any insight?


Registering takes place as follows:

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

Where "messageReceiver" is defined as

private newMessage messageReceiver = new newMessage();

IMService.NEW_MESSAGE is merely a 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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