Уведомление о пожарной базе и данные
Я создаю приложение, используя Firebase cloud messaging api.. Я могу отправлять уведомления и данные в мое клиентское приложение с сервера.
Но проблема заключается в том, что когда приложение открыто, уведомление не срабатывает, пока данные будут получены (я имею в виду, что я зарегистрировал его). Это не проблема. Но когда приложение закрыто, уведомление получено, а я нажал на уведомление о том, что действие пока я не смогу увидеть данные журнала. Мне нужно обновить данные в texView..
My MyFirebaseMessagingService:
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
Log.e("FROM", "From: " + remoteMessage.getFrom());
String data = remoteMessage.getData().get("message");
Log.e("KOIII", "Notification Message Body: " + remoteMessage.getNotification().getBody());
// showNotificationS(remoteMessage.getNotification().getBody(),2);
if(data.equals("true")){
Log.e("DATA", "SUCCESS");
// Fragment1.getInstace().updateTheTextView(data, data, data);
}
}
Мой манифест:
<activity
android:name=".SplashScreen"
android:label="@string/app_name"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".myHome"
android:label="@string/app_name">
</activity>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Ответы
Ответ 1
Когда вы отправляете сообщение уведомления с полезной нагрузкой (уведомлением и данными), а приложение находится в фоновом режиме, вы можете получить данные из дополнительных функций намерения, которые запускаются в результате нажатия пользователем уведомления.
Из образец FCM, который запускает MainActivity при прослушивании уведомления:
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
Ответ 2
FCM не будет показывать уведомление, если ваше приложение находится на переднем плане, поэтому вы вручную показываете, что вот так: -
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// 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.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "From: " + remoteMessage.getData().get("message"));
// Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getData().get("message"));
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MarketActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Fred Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}