具体 activity 当应用程序不在前台时无法通过通知点击打开(应用程序在最近,没有被杀死!)

Specific activity not opening from notification click when the app is not in foreground(app is in recents, not killed!)

我想在通知点击时打开特定 activity。但是当应用程序在后台时,它不会打开。我什至没有传递附加信息(即数据)。我只想打开 activity 并根据登录的用户执行一些任务。我什至尝试在通知点击时打开我的默认启动器 activity,然后从那里将用户发送到通知 activity。这是我的默认启动器 activity 的代码: PS:我正在从 firebase 控制台发送消息,但它只有标题和 body。

(这是我完成网络任务后调用的函数:)

        if (list.size()!=0){
            for (int i=0;i<list.size();i++){
                Users u=list.get(i);
                //Toast.makeText(LoginActivity.this, "Logging in...", Toast.LENGTH_SHORT).show();
                final Intent intent;
                Bundle b=new Bundle();
// This is the solution i found to check whether the extras has the package name or not! But it doesnt seem to work.
                if (Splashscreen.this.getIntent().getExtras() != null){
                    if (Splashscreen.this.getIntent().hasExtra("pushnotification") || Splashscreen.this.getIntent().getExtras().containsKey("com.tracecost")){
                        System.out.println("From notification----------->");
                        intent=new Intent(Splashscreen.this,NotificationReceivedActivity.class);
                        b.putString("pushnotification","yes");
                    }
                    else{
                        intent=new Intent(Splashscreen.this, ProjectSelection.class);
                    }
                }
                else{
                    intent=new Intent(Splashscreen.this, ProjectSelection.class);
                }

                b.putSerializable("user",u);
                b.putSerializable("projectlist",plist);
                intent.putExtras(b);
                //logginDialog.dismiss();
                Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(intent);
                        finish();
                    }
                },3500);

            }
        }
    }```

这仅在应用程序处于前台时有效。当应用程序在后台时,它只考虑来自负载的通知数据并忽略数据部分。这导致无法控制应用程序,因为通知类型消息将由系统单独处理。唯一的选择是使用您自己的外部服务器或从其他客户端发送。

只要您发送 data.

,当应用程序处于前台或后台时,您可以从 Firebase 通知重定向

我将为您提供一个示例,说明如何根据从通知收到的密钥在活动之间重定向,firebase 神奇地处理其余部分。

P.S: If you want to handle the activity that is already open in the background, use taskAffinity to play around.

通过FirebaseMessagingService处理Firebase数据:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    System.out.println("MESSAGE BODY :" + remoteMessage.toString());
    if (remoteMessage.getData().size() > 0) {
        //getting the title and the body
        String redirect;
        String title = remoteMessage.getData().get("message_title");
        String body = remoteMessage.getData().get("message_body");
        redirect = remoteMessage.getData().get("redirect");
        String event_id = remoteMessage.getData().get("event_id");
        System.out.println("PUSH MESSAGE = " + remoteMessage.toString());
        JSONObject jsonData = new JSONObject(remoteMessage.getData());
        System.out.println("RESPONSE :" + jsonData.toString());
        if (redirect != null) {
            sendNotification(title, body, event_id, redirect);
        } else {
            redirect = "";
            sendNotification(title, body, event_id, redirect);

        }
    }
}


private void sendNotification(String title, String body, String event_id, String redirect) {
    Intent backIntent = new Intent();
    PendingIntent pendingIntent;
    if (redirect.contentEquals("CHAT")) {
        backIntent = new Intent(MyFirebaseMessagingService.this, ChatScreen.class);
        backIntent.putExtra("item_id", event_id);
    }
    if (redirect.contentEquals("EVENT") || redirect.contentEquals("INVITATION")) {
        backIntent = new Intent(MyFirebaseMessagingService.this, Event_Summary.class);
        backIntent.putExtra("event_id", event_id);
    }
    backIntent.putExtra("MODE", "FIRE_NOTIFICATION");
    backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(backIntent);
    pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}

Firebase 控制台仅发送通知消息(更多信息请点击此处Firebase)但您可以使用自己的服务器或 Firebase API 发送数据消息.

数据消息适用于前台和后台应用状态。

触发推送通知的示例 curl 如下所示:

curl -X POST \ https://fcm.googleapis.com/fcm/send \ -H 'Authorization: key=YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -H 'cache-control: no-cache' \ -d '{ "data": { "title":"TITLE", "message":"Notification Content", "custom_key": "custom_value" }, "registration_ids": ["DEVICE_PUSH_TOKEN"] }'

您也可以传递您的自定义键值对,并在 onMessageReceived 方法中获取它们。

注意:在这种方法中,您必须创建在系统托盘中可见的通知。示例代码如下所示:

// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that will fire when the user taps the notification
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

您可以在 official documentation

中找到更多相关信息

希望对您有所帮助!