Как я должен отправить идентификатор документа вместе с уведомлением? - PullRequest
0 голосов
/ 26 октября 2019

Я использую приведенный ниже код для отправки уведомления в Android с помощью облачного обмена сообщениями Firebase. Я хочу отправить идентификатор документа вместе с уведомлением, чтобы при нажатии на уведомление приложение открывалось для определенного действия, где этот конкретный идентификатор документатребуется, это в основном комментарий, понравившийся пользователю сообщения, и когда уведомление получено после нажатия, мне нужен идентификатор документа публикации, чтобы я мог отослать его к списку комментариев и получить конкретный список комментариев, которые должны быть получены

Код

public void notificationlike(){JSONObject notification = new JSONObject();
                JSONObject notifcationBody = new JSONObject();
                try {
                    notifcationBody.put("title", PostTitle);
                    notifcationBody.put("message", notificationMessage);

                    notification.put("to", CommentAuthorTokenID);
                    notification.put("data", notifcationBody);

                    Log.d(TAG, "Notification Success1  " + CommentAuthorTokenID );
                } catch (JSONException e) {
                    Log.e(TAG, "onCreate: " + e.getMessage() );
                }
                sendNotification(notification);



}

private void sendNotification(JSONObject notification) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i(TAG, "onResponse: " + response.toString());
                        }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(CommentActivity.this, "Request error", Toast.LENGTH_LONG).show();
                        Log.i(TAG, "onErrorResponse: Didn't work");
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Authorization", serverKey);
                params.put("Content-Type", "application/json; charset=utf-8");
                return params;
            }
        };
        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);// class for requestQueue
    }

Построитель уведомлений

    final Intent intent = new Intent(this, CommentActivity.class);
   // intent.putExtra( "PostKey",  PostId );
    NotificationManager notificationManager = (NotificationManager)getSystemService( Context.NOTIFICATION_SERVICE);
    int notificationID = new Random().nextInt(3000);

  /*
    Apps targeting SDK 26 or above (Android O) must implement notification channels and add its notifications
    to at least one of them. Therefore, confirm if version is Oreo or higher, then setup notification channel
  */
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        setupChannels(notificationManager);
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this , 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_heart_normal);

    Uri notificationSoundUri = RingtoneManager.getDefaultUri( RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_heart_selected)
            .setLargeIcon(largeIcon)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("message"))
            .setAutoCancel(true)
            .setSound(notificationSoundUri)
            .setContentIntent(pendingIntent);

    //Set notification color to match your app color template
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        notificationBuilder.setColor(getResources().getColor( R.color.colorPrimaryDark));
    }
    notificationManager.notify(notificationID, notificationBuilder.build());

1 Ответ

0 голосов
/ 26 октября 2019

Согласно документу Firebase

https://firebase.google.com/docs/cloud-messaging/server#xmpp-request

Появилось новое поле 'message_id', укажите его, затем извлеките его в ответной стороне

...