[英]How to handle the Firebase notification when app is in foreground
我已將Firebase Cloud Messaging與我的應用程序集成在一起。 當我從Firebase控制台發送通知時,如果該應用程序在后台或未打開,則我會成功收到該通知,否則,如果該應用程序在前台或已打開,則不會收到該通知。
所有建議表示贊賞。
當應用程序處於前台時,不會自行生成通知。 您需要編寫一些其他代碼。 收到消息后,將調用onMessageReceived()
方法,您可以在其中生成通知。 這是代碼:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
當應用程序處於前台狀態時, FirebaseMessagingService
永遠無法工作。 在這種情況下,如果您想從FCM接收消息,則WakefulBroadcastReceiver
將為您工作
public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadcastReceiver::", "BroadcastReceiver");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(intent.getExtras().getString("title"))
.setContentText(intent.getExtras().getString("message"));
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
將firebase
與Play商店中的GCM
鏈接,並在清單中編寫以下代碼
<receiver
android:name=".firebase.FirebaseDataReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.