如何在收到推送通知时自动打开应用程序?

Mau*_*aus 9 android push-notification firebase firebase-cloud-messaging

我想在收到推送通知时自动打开应用程序。我已经尝试过,但它仍然无法按我的预期工作。下面的代码在应用程序处于活动状态或处于 MainActivity 中时有效,但当应用程序在后台或仅在托盘上显示通知时则不起作用。我错过了什么?

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);
}
}
Run Code Online (Sandbox Code Playgroud)

RKS*_*RKS 4

这是需要从后端处理的事情,

这是您现在正在使用的示例有效负载, { "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "title":"Portugal vs. Denmark", "body":"great match!" } } }

当您的应用程序位于前台时,这只会让您控制操作并执行某些操作,否则只需发出通知。

详细信息你可以在这里查看。

现在,为了始终控制您的通知,您需要如下所示的有效负载,

{ "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "data":{ "Nick" : "Mario", "body" : "great match!", "Room" : "PortugalVSDenmark" } } }

不同之处在于您需要发送数据负载而不是来自后端的通知负载。