3

如何知道应用程序是否从 android 通知托盘打开?例如,我已经关闭了应用程序(从最近的应用程序列表中清除)。但我收到来自后端 websocket 的通知,我按下它,它打开了应用程序。所以我的问题是,有没有办法检查这是否从通知中打开?

4

2 回答 2

2

查看react-native-push-notification的来源+ 接下来的 50 行(最多setContentIntent),您可以检查意图中额外的“通知”。

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getBundleExtra("notification");
        if(bundle != null){
            //check if it is the bundle of your notification and do your thing
        }
    }

否则,您可以使用本机模块方法:

当您设置PendingIntent传递给通知.setContentIntent()方法的内容时,请指定您随后在应用程序中恢复的操作。示例通知:

Intent intent = new Intent(context, MyActivity.class);
intent.setAction("OPEN_MY_APP_FROM_NOTIFICATION");
NotificationCompat.Builder mNotifyBuilder = NotificationCompat.Builder(this, CHANNEL)
            .setContentTitle("Title")
            .setContentIntent(PendingIntent.getActivity(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT))            
mNotificationManager.notify(Notification_REQUEST_CODE,
                                    mNotifyBuilder.build())

在 MyActivity.java

public void onCreate (Bundle savedInstanceState) {
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    if(action == "OPEN_MY_APP_FROM_NOTIFICATION"){
         //do whatever you have to do here
    }
}

附加信息: 处理意图 创建意图

于 2018-10-01T19:05:51.967 回答
2

很简单,您在推送通知侦听器中接收通知有效负载

import PushNotification from 'react-native-push-notification'
configurePushNotifications = () => {

    PushNotification.configure({
      // (optional) Called when Token is generated (iOS and Android)
      onRegister: function(token) {
        console.log('PushNotification token', token)
      },

onNotification 是您接收本地或远程通知的地方,当用户单击通知托盘时将调用它

      onNotification: function(notification) {
        console.log('notification received', notification)
      },

      // IOS ONLY (optional): default: all - Permissions to register.
      permissions: {
        alert: true,
        badge: true,
        sound: true,
      },

      // Should the initial notification be popped automatically
      // default: true
      popInitialNotification: true,

      /**
       * (optional) default: true
       * - Specified if permissions (ios) and token (android and ios) will requested or not,
       * - if not, you must call PushNotificationsHandler.requestPermissions() later
       */
      requestPermissions: true,
    })
  }

这就是通知对象的样子

{
    foreground: false, // BOOLEAN: If the notification was received in foreground or not
    userInteraction: false, // BOOLEAN: If the notification was opened by the user from the notification area or not
    message: 'My Notification Message', // STRING: The notification message
    data: {}, // OBJECT: The push data
}
于 2018-10-01T20:49:56.837 回答