[英]onMessageReceived is not executing when the app is in background
當我打開應用程序並收到通知時,會顯示我的自定義通知。
但是當應用程序在后台時,它只是使用默認的通知設置。 我正在嘗試將通知的圖標從那個點更改為我的應用程序徽標。
我的 FirebaseMessagingService 代碼如下
public static final String TG = "FCMService";
NotificationManagerCompat notificationManager;
@Override
public void onNewToken(@NonNull String s) {
Log.i(TG, "The token refreshed: " + s);
super.onNewToken(s);
}
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getData().size() > 0)
{
Log.d(TG, "Message data payload : " + remoteMessage.getData());
}
if(remoteMessage.getNotification() != null)
{
Log.d(TG, "Message notification body : " + remoteMessage.getNotification().getBody());
}
Log.d(TG, "From : " + remoteMessage.getFrom());
Map<String, String> s = remoteMessage.getData();
sendNotification(s.get("message"));
}
private void sendNotification(String message) {
notificationManager = NotificationManagerCompat.from(this);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 ,intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_07c1b5098af03f95f3c3e8f7d461fb78)
.setContentTitle("Just In")
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(1, notification);
}
我的清單文件是
<service
android:name=".MyFirebaseMessagingService"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
有兩種類型的消息數據消息和通知消息。 無論應用程序是在前台還是后台,數據消息都在 onMessageReceived 中處理。 數據消息是傳統上與 GCM 一起使用的類型。 只有當應用程序在前台時,才會在 onMessageReceived 中接收通知消息。 當應用程序在后台時,會顯示一個自動生成的通知。 當用戶點擊通知時,他們將返回到應用程序。 包含通知和數據有效負載的消息被視為通知消息。 Firebase 控制台始終發送通知消息。
示例代碼:-您需要像這樣在通知有效負載中指定圖標
$notification = array
(
'icon' => 'icon here',
'title' => 'title',
'body' => 'new msg',
'click_action' => 'action here'
);
注意:-您需要在清單中添加這些才能使用這樣的默認通知圖標
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_launcher" />
// optional if required
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/notification_color" />
參考 Firebase,當你的應用在后台時,通知會發送到設備的系統托盤。 默認情況下,用戶點擊通知會打開應用啟動器。
在后台接收時包含通知和數據有效負載的消息。 在這種情況下,通知被傳遞到設備的系統托盤,數據負載被傳遞到啟動器 Activity 的附加內容中。
Android Pie 和較新的版本有一些限制。 檢查此參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.