sendBroadcast does not get called in Activity when Activity is opened

别来无恙 提交于 2020-01-03 02:29:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!