I'm able to send a push notification to my App with FCM services. I'm doing that using POSTMAN/INSOMNIA.
Everything is working fine. I can see the notification. But I need some advice / point to the right direction when it comes to processing the incoming message.
I've set up everything using the FCM official documentation.
My server call looks like this:
{
"to":"...",
"data" : {
"sound" : "default",
"body" : "Message body",
"title" : "My APP",
"content_available" : true,
"priority" : "high",
"my_message": "123456"
}
}
I can access the data in the onMessageReceived() method:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
// get incoming data
}
}
So far nothing extraordinary. What I'd like to achieve is if my Activity is in foreground I don't need to display the taskbar notification, just to show the message which comes with my FCM message (the my_message key)) inside my Activity. Is that possible?
If the app is in background I'd like to open a Activity (that I'm able to do) and pass to the Intent my data (the message above) This is what I'm struggling.
If the 'App in Background' scenario happens, my notification is displayed this way:
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "my_channel_id";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_person)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"DG_Channel",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
So my 3 main questions are:
- can I tell if my app is in foreground/background when the notification arrives?
- If in foreground how can I access the data from activity
- if in background, how can I pass data to the activity
Thank's for any advice