Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...