Сохранить FCM Push-уведомление как сообщения во фрагменте - PullRequest
0 голосов
/ 28 января 2019

Это мой первый вопрос.Я подключил свой домен в FireBase.Push-уведомление работает, когда я обновляю сообщение в своем блоге Wordpress.Хорошо, пока это хорошо.Но я хочу сохранить все эти уведомления во фрагменте, и их можно щелкнуть оттуда, чтобы начать действие для идентификатора записи.Как сохранить это уведомление?Вот мой код сообщения Firebase:

private static int VIBRATION_TIME = 500; // in millisecond
private SharedPref sharedPref;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    sharedPref = new SharedPref(this);
    if (sharedPref.getNotification()) {
        // play vibration
        if (sharedPref.getVibration()) {
            ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(VIBRATION_TIME);
        }
        RingtoneManager.getRingtone(this, Uri.parse(sharedPref.getRingtone())).play();

        if (remoteMessage.getData().size() > 0) {
            Map<String, String> data = remoteMessage.getData();
            FcmNotif fcmNotif = new FcmNotif();
            fcmNotif.setTitle(data.get("title"));
            fcmNotif.setContent(data.get("content"));
            fcmNotif.setPost_id(Integer.parseInt(data.get("post_id")));
            displayNotificationIntent(fcmNotif);
        }
    }
}

private void displayNotificationIntent(FcmNotif fcmNotif) {
    Intent intent = new Intent(this, ActivitySplash.class);
    if (fcmNotif.getPost_id() != -1) {
        intent = new Intent(this, ActivityPostDetails.class);
        Post post = new Post();
        post.title = fcmNotif.getTitle();
        post.id = fcmNotif.getPost_id();
        boolean from_notif = !ActivityMain.active;
        intent.putExtra(ActivityPostDetails.EXTRA_OBJC, post);
        intent.putExtra(ActivityPostDetails.EXTRA_NOTIF, from_notif);
    }
    PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(fcmNotif.getTitle());
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText(fcmNotif.getContent()));
    builder.setContentText(fcmNotif.getContent());
    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setDefaults(Notification.DEFAULT_LIGHTS);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        builder.setPriority(Notification.PRIORITY_HIGH);
    }
    builder.setContentIntent(pendingIntent);
    builder.setAutoCancel(true);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    int unique_id = (int) System.currentTimeMillis();
    notificationManager.notify(unique_id, builder.build());
}

}

Ответы [ 2 ]

0 голосов
/ 28 января 2019

Вы можете сохранить уведомление, когда уведомление поступило внутрь

onMessageReceived (RemoteMessage remoteMessage)

, например, таким способом

Полный примеруведомление, как это ..

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    try {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        Map<String, String> data = remoteMessage.getData();
        String value1 = data.get("key_1");
        String value2 = data.get("key_2");
        String title=data.get("title");
        String msg=data.get("body");
        Log.d("Backgraound", value1);
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        sendNotification(title,msg,value1,value2);
    }catch (Exception e){
        Log.d("Error Line Number",Log.getStackTraceString(e));
    }
}

private void sendNotification(String title,String messageBody, String val1,String val2) {
    try {
        Intent intent = new Intent(this, Notification_activity.class);
        //Bundle bundle = getApplicationContext().getExtras();
        Bundle basket = new Bundle();
        basket.putString("key_1", val1);
        basket.putString("key_2", val2);
        intent.putExtras(basket);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.spacebar_round)
                        .setContentTitle(title)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent)
                        .setColor( getResources().getColor(R.color.colorPrimary))
                        .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
                                R.mipmap.ic_launcher));

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }catch (Exception e){
        Log.d("Error Line Number",Log.getStackTraceString(e));
    }
}
}
0 голосов
/ 28 января 2019

да, вы можете сохранить полезную нагрузку Notification в базе данных, создать фрагмент по фрагменту, отобразить данные из базы данных и щелкнуть по любой активности начала строки в соответствии с идентификатором записи, получив идентификатор записи по позиции

...