I want to automatically open app when receive push notification. I've tried but it still does not work as I expected. This code below is work when the app is active or in MainActivity, but it's not work when the app in the background or just show notification on tray. Did I miss something?
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
if (PreferencesUtil.getInstance(this).isLoggedIn()) {
sendNotification(remoteMessage.getData().get("order_id"));
}
}
}
public void sendNotification(String messageBody) {
NotificationManager notificationManager = null;
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder;
notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Notification")
.setSmallIcon(R.mipmap.icon_notif)
.setContentText(messageBody)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_LIGHTS );
//add sound
try {
Uri sound = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.siren);
Ringtone ringtone = RingtoneManager.getRingtone(this, sound);
ringtone.play();
notificationBuilder.setSound(sound);
} catch (Exception e) {
e.printStackTrace();
}
//vibrate
long[] v = {1000, 1000, 1000, 1000, 1000};
notificationBuilder.setVibrate(v);
notificationManager.notify(0, notificationBuilder.build());
Intent i = new Intent(this, NotificationActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
}
This is something need to handle from backend,
Here is a sample payload you are using right now,
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
Which will only give you control to manipulate and do some action when your app will be in foreground otherwise just raise notification.
In details you can check here.
Now, To always get control over your notification, you need payload like following,
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
The difference is you need to send data payload instead of notification poayload from backend.