如何在app处于前台时处理fire base通知

时间:2016-07-19 06:42:41

标签: android firebase-cloud-messaging android-broadcastreceiver

我已将Fire基础云消息传递与我的应用程序集成。 当我从firebase控制台发送通知时,如果app处于后台/未打开,那么我收到通知,

但在应用处于前台/开放时无法接收通知

所有建议都表示赞赏。

2 个答案:

答案 0 :(得分:43)

当应用程序位于前台时,通知不会自行生成。您需要编写一些额外的代码。当收到消息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());
}

}

答案 1 :(得分:2)

当应用程序处于前台时,

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());
        }
    }

在Play商店中将firebaseGCM相关联,并在清单

中写下以下代码
<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>