Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

broadcastreceiver - 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?

EDIT
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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure if it is specific to the set up, or if it is a fix in general, but moving the register/unregister to the onResume/onPause _respectively_ and not registering in the onCreate solved the problem for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...