let me discuss with you a scenario, let the app be in the foreground with Activity "X" opened. Now my app received a notification through Firebase Messaging Service. What I want? I want that if my app is in the foreground, my activity "X" could detect if I received a notification so that I could switch an icon.
Here's my code for the Firebase Messaging Service:
@Override
public void onMessageReceived(RemoteMessage message){
type=message.getData().get("type");
CrucialData.setReceivedNotificationWithoutChecking(true);
createNotification(message);
}
private void createNotification(RemoteMessage message) {
Context context = getBaseContext();
checkingIfAppIsInForeground(context);
if(!inForeground){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.appicon)
.setColor(getResources().getColor(R.color.colorPrimaryDark))
.setContentTitle("Your chat is going to expire tomorrow!")
.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, main_activity.class);
resultIntent.putExtra("launchedFromNotification",true);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(main_activity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mNotificationId is a unique integer your app uses to identify the
mNotificationManager.notify(1231, mBuilder.build());
}
You could use a Local Broadcast to communicate between your service and activity.
Here's an example.