Как узнать, открыто ли приложение из панели уведомлений Android? - PullRequest
0 голосов
/ 01 октября 2018

Как узнать, открыто ли приложение из панели уведомлений Android?Например, я закрыл приложение (очищено из списка последних приложений).но я получаю уведомление от бэкэнда websocket, я нажал его, он открывает приложение.Итак, мой вопрос, есть ли способ проверить, если это открыто из уведомления?

Ответы [ 2 ]

0 голосов
/ 01 октября 2018

Это просто, вы получаете полезную нагрузку уведомлений в прослушивателе push-уведомлений

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
}
0 голосов
/ 01 октября 2018

Глядя на источник реагировать-родной-push-уведомления + следующие 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
    }
}

Дополнительная информация: Цели обработки Создание элементов

...