我想在收到推送通知时自动打开应用程序。 我已经尝试过了,但它仍然没有像我预期的那样工作。 下面的代码在应用程序处于 Activity 状态或在 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);
}
}
最佳答案
这是需要后台处理的事情,
这是您现在使用的示例负载,
{
“信息”:{
“ token ”:“bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1 ...”,
“通知”:{
"title":"葡萄牙对丹麦",
“ body ”:“非常匹配!”
}
}
}
当您的应用程序处于前台时,这只会让您控制操作和执行某些操作,否则只会发出通知。
详细可以查看here .
现在,为了始终控制您的通知,您需要如下有效载荷,
{
“信息”:{
“ token ”:“bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1 ...”,
“数据”:{
“尼克”:“马里奥”,
"body": "绝配!",
“房间”:“葡萄牙VS丹麦”
}
}
}
区别在于您需要发送数据负载而不是从后端发送通知负载。
关于android - 如何在收到推送通知时自动打开应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50368716/