Push-уведомление показывает оповещение, содержащее JSON с cordova-plugin-fcm, cordova, angular и firebase с приложением на переднем плане - PullRequest
0 голосов
/ 02 октября 2018

image of notification У меня есть приложение Cordova / Angular, использующее firebase для push-уведомлений через плагин cordova-plugin-fcm.Уведомления отображаются на панели должным образом, когда приложение закрыто / в фоновом режиме, но когда приложение открывается посредством нажатия на уведомление на панели (или уже открыто), само уведомление представляет собой просто окно предупреждения, которое содержит объект предупреждения JSON,Вместо отформатированного уведомленияне читается человеком.

здесь представлен объект JSON, отправляемый через REST API:

{  
   "to":"/topics/all",
   "priority":"high",
   "notification":{  
   "title":"App in Foreground Test",
   "body":"Test App in Foreground",
   "sound":"default",
   "click_action":"FCM_PLUGIN_ACTIVITY",
   "icon":"fcm_push_icon"
},
 "data":{  
   "title":"App in Foreground Test",
   "message":"Test with app in Foreground",
   "param1":"value1",
   "param2":"value2"
 }
  }

Отправка уведомлений и полезных данных, поэтому я получаю уведомления, когда приложение находится в фоновом и переднем плане.

    public static void sendPushPayload(Map<String, Object> payload) {
    Log.d(TAG, "==> FCMPlugin sendPushPayload");
    Log.d(TAG, "\tnotificationCallBackReady: " + notificationCallBackReady);
    Log.d(TAG, "\tgWebView: " + gWebView);
    try {
        JSONObject jo = new JSONObject();
        for (String key : payload.keySet()) {
            jo.put(key, payload.get(key));
            Log.d(TAG, "\tpayload: " + key + " => " + payload.get(key));
        }
        String callBack = "javascript:" + notificationCallBack + "(" + jo.toString() + ")";
        if(notificationCallBackReady && gWebView != null){
            Log.d(TAG, "\tSent PUSH to view: " + callBack);
            gWebView.sendJavascript(callBack);
        }else {
            Log.d(TAG, "\tView not ready. SAVED NOTIFICATION: " + callBack);
            lastPush = payload;
        }
    } catch (Exception e) {
        Log.d(TAG, "\tERROR sendPushToView. SAVED NOTIFICATION: " + e.getMessage());
        lastPush = payload;
    }
}

1 Ответ

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

Вы получаете «некрасивый» JSON в уведомлении, потому что вы добавляете тело сообщения непосредственно как содержимое уведомления.

.setContentText(messageBody)

Извлеките соответствующую информацию из messageBody и добавьтеэту информацию в .setContentText().

Чтобы получить данные из части data, вы можете добавить что-то подобное в ваш onMessageReceived() метод:

if (remoteMessage.getData().size() > 0) {
    message = getDataWithKey(remoteMessage.getData(), "message");
    title = getDataWithKey(remoteMessage.getData(), "title");
    param1 = getDataWithKey(remoteMessage.getData(), "param1");
    param2 = getDataWithKey(remoteMessage.getData(), "param2");
}

Затем добавьте этот метод:

private String getDataWithKey(Map<String, String> params, String fieldKey) {
    String data = "";
    try {
        for (Map.Entry<String, String> param : params.entrySet()) {
            String key = param.getKey();
            String value = param.getValue();
            if(key.contentEquals(fieldKey)){
                if(!value.isEmpty()) {
                    data = value;
                }
            }
        }
    }
    catch (Exception ex){
        Log.e(TAG, "  getDataWithKey -- " + ex.getMessage());
    }
    return data;
}



РЕДАКТИРОВАТЬ

«Уродливое» уведомление не приходит от Notification оно приходитоткуда-то еще в вашем коде, потому что это те же самые данные, которые добавляются в этот код:

Map<String, Object> data = new HashMap<String, Object>();
    data.put("wasTapped", false); 
...

Я вижу, что вы используете по крайней мере в двух местах:

FCMPlugin.sendPushPayload( data );

и

for (String key : data.keySet()) {
    intent.putExtra(key, data.get(key).toString());
}


Также учтите: Для более новых версий ОС Android требуется NotificationChannel для правильной работы.Пример кода (вам необходимо изменить некоторые его части в соответствии с вашими потребностями):

private void sendNotification(String title, String messageBody, Map<String, Object> data) {
    try{
        Intent intent = new Intent(this, BusinessDetailActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        for (String key : data.keySet()) {
            intent.putExtra(key, data.get(key).toString());
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                                                                0,
                                                                intent,
                                                                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT); // PendingIntent.FLAG_ONE_SHOT);

        String idNotification = createNotificationChannel();
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, idNotification)
                .setContentTitle(title)
                .setContentText(body)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setCategory(NotificationCompat.CATEGORY_PROMO)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)
                .setSmallIcon(SMALL_ICON);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            //TODO: You will need to define your own ID_NOTIFICATION!!
            notificationBuilder.setChannelId(ID_NOTIFICATION);
        }

        NotificationManager notificationManager = getSystemService(NotificationManager.class);

        //TODO: I use a random number generator, but you do what fits your needs
        int idNot = CodeGenerator.getRandomNumber(10, 10000);
        assert (notificationManager != null);
        notificationManager.notify(idNot, notificationBuilder.build());
    }
    catch (Exception ex){
        Log.e(TAG, "  sendNotification --- " + ex.getMessage());
    }
}



private String createNotificationChannel() {
    //TODO: You will need to define your own ID_NOTIFICATION!!
    String id = ID_NOTIFICATION;
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String name = "Special Notification";
            String desc = "Notification showing special information.";
            int prio = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(id, name, prio);
            channel.setShowBadge(true);
            channel.setDescription(desc);
            channel.setLightColor(Color.RED);
            channel.enableLights(true);
            channel.enableVibration(true);

            NotificationManager manager = getSystemService(NotificationManager.class);
            assert (manager != null);
            manager.createNotificationChannel(channel);
        }
    }
    catch (Exception ex){
        Log.e(TAG, ex.getMessage());
    }
    return id;
}
...