为什么当程序是前台并且只能在后台运行时,Firebase通知无法接收?

时间:2017-09-05 09:48:21

标签: android firebase-cloud-messaging

为什么程序在前台时不会收到Firebase通知,只在程序在后台运行时才收到通知。

我的代码是

public class MyFirebaseMessagingService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
 sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));

2 个答案:

答案 0 :(得分:0)

检查您的AndroidManifest.xml文件。您的服务定义应该是这样的

 <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>

 </service>

如果未添加intent-filter,您的应用将无法在前台收到通知。

答案 1 :(得分:0)

修改代码:当应用程序在前台时,您将获得通知而不是数据,因此获取数据为getNotification()。getTitle()和其他所需的东西

public void onMessageReceived(RemoteMessage remoteMessage) {
  Intent intent = new Intent(this, MainActivity.class);
  //System.currentTimeMillis is unique ID
  PendingIntent contentIntent = PendingIntent.getActivity(this, (int) 
  System.currentTimeMillis(), intent,0);
     NotificationCompat.Builder mBuilder = new NotificationCompact.Builder(this) 
                   .setContentTitle(remoteMessage.getNotification().getTitle())
                    .setContentText(remoteMessage.getNotification().getBody())
                    .setContentIntent(contentIntent).setAutoCancel(true)
                    .setSmallIcon(R.drawable.ic_launcher);
  NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());

Intent和PendingIntent用于在单击Notification

时打开Activity

通知构建器,用于设置显示的通知的标题和正文

NotificationManager用于创建通知。