问题
I am making an app where I receive XMPP packets. My app starts in foreground and starts a Sticky Service if not started and start receive messages in backgrounds and make notifications of them. The notifications works well and when clicked they show the data. Issue comes (that too sometimes in some mobile phones) when I make a sendBroadcast call from service so that I can asynchronously update the text of message in Activity when it is opened.
My app is made with a Activity and within that there are two Fragments(SherlockFragment)
So I made a private broadcastreceiver in one of fragment where I want to show the text (updated text).
Code is written below
public class newMessage extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.v("ONMESSAGE", "broadcast");
String action = intent.getAction();
if(action.equalsIgnoreCase("NewMessage")){
Bundle extra = intent.getExtras();
String username = extra.getString("from");
String message = extra.getString("message");
showMessage(username, message);
Log.v("ONMESSAGE", "in broadcast is " + username);
}
}
}
I then make a statement of below in Fragment class
private newMessage messageReceiver = new newMessage();
in onCreateView I wrote the below line
getActivity().registerReceiver(messageReceiver, new IntentFilter("NewMessage"));
I did not unregister the broadcast receiver now and I tried doing that too.
When I receive a message in my service, I made call to below code.
Intent i = new Intent("NewMessage");
i.putExtra("message", message);
i.putExtra("from", from);
context.sendBroadcast(i);
I did not add the broadcats to to manifest cause I dont know how to do it when written inside a class.
Sometimes, it calls the sendbroadcase and everything works well however sometimes it does not call and just generate the notification.
来源:https://stackoverflow.com/questions/25057531/sendbroadcast-does-not-get-called-in-activity-when-activity-is-opened