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);
}
}