Reputation: 1037
I try to send broadcast to fragment when notification arrived. I think I've done everything ok, but it doesn't work. Could you tell me what am I doing wrong ? This is how I send broadcast:
if (code == 1) {
int id = Integer.parseInt(data[1]);
int idMessage = Integer.parseInt(data[2]);
String user = data[3];
String messageChat = data[4];
Intent intent2 = new Intent(arg0, ChatMainActivity.class);
intent2.putExtra("alert", true);
intent2.putExtra("userId", id);
intent2.putExtra("messageId", idMessage);
intent2.putExtra("userName", user);
intent2.putExtra("message", messageChat);
intent2.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent2.setAction("mac.baseline.baselinemobile.BroadcastReceiver");
sendBroadcast(intent2);
PendingIntent pIntent = PendingIntent.getBroadcast(arg0, 0,
intent2, 0);
boolean isRunning = isApplicationRunning();
if (isRunning) {
intent2 = new Intent(arg0, AlertReceiver.class);
pIntent = PendingIntent.getBroadcast(arg0, 0, intent2, 0);
}
Notification notification = new NotificationCompat.Builder(arg0)
.setContentTitle("Baseline™")
.setContentText("Nowa wiadomość od: " + user + ": " + messageChat)
.setSmallIcon(R.drawable.alert2)
.setTicker(newItems)
.setContentIntent(pIntent).build();
and this is how I receive it in my fragment :
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive: works!");
}
};
public void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("mac.baseline.baselinemobile.BroadcastReceiver");
LocalBroadcastManager.getInstance(getActivity()).
registerReceiver(mReceiver, filter);
}
public void onPause()
{
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
Upvotes: 1
Views: 999
Reputation: 738
Not sure how you are using the app. But you need to do..
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
And do the register and unregister operation in onCreate() and onDestroy() method.
Upvotes: 2
Reputation: 4959
Write this line
LocalBroadcastManager.getInstance(getApplicationContext).sendBroadcast(intent2);
instead of
sendBroadcast(intent2);
Upvotes: 1