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

标签 android firebase push-notification firebase-cloud-messaging

我想在收到推送通知时自动打开应用程序。 我已经尝试过了,但它仍然没有像我预期的那样工作。 下面的代码在应用程序处于 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/

相关文章:

android - com.huawei.hms :push:5. 3.0.301 中不推荐使用 "AGConnectServicesConfig"类

javascript - 为什么 update() 会完全覆盖我在 Firebase 中的数据? set() 与 update()

java - 如何识别此错误 "java.lang.NullPointerException"的来源?

ios UIApplicationOpenURLOptionsKey 不适用于 Firebase

push-notification - 根据新的 API,APNS 反馈服务是否不再存在?

android - 如何在信息窗口中显示相应标记的适当的多个数据

android - 如何在 firemonkey 中将敏感数据保存为密码?

java - 为什么添加firebase后更新apk安装失败?

android - 查明当应用程序在后台时收到 Firebase 消息的时间

ios - 推送通知声音不起作用