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"
So, in your activity, create your custom handler and pass it to your service. So, when you wants to put some data to your activity, you can put handler. sendMessage() in your Service (it will call handleMessage of your innerClass). Show activity on this post.
Step 1. Open your project where you want to implement this. Step 2. Open your BroadcastReceiver class from where you pass data to activity inside your onReceive() you need to start intent and pass data inside intent and start sendBroadcast() as shown bellow.
As an Android developer, you'll often run into the scenario where you need to perform tasks and display notifications for your app in the background. To retain battery power on our users device we are going to run background tasks using a broadcast receiver.
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.
Try this two things:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With