首页 > 解决方案 > Android:通知未使用 Firebase 云消息传递给用户

问题描述

Firebase Cloud Message第一次使用。我将我的应用程序连接到Firebase并使用了本教程,但没有任何通知

这是我的代码。

在里面AndroidManifest.xml

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

MyFirebaseInstanceIDService

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService  {
private static final String TAG = "MyFirebaseIIDService";
private static final String FRIENDLY_ENGAGE_TOPIC = "football";
@Override
public void onTokenRefresh() {
    String token = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "FCM Token: " + token);

    // Once a token is generated, we subscribe to topic.
    FirebaseMessaging.getInstance()
            .subscribeToTopic(FRIENDLY_ENGAGE_TOPIC);
   }
}

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFMService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Handle data payload of FCM messages.
    Log.d(TAG, "FCM Message Id: " + remoteMessage.getMessageId());
    Log.d(TAG, "FCM Notification Message: " +
            remoteMessage.getNotification());
    Log.d(TAG, "FCM Data Message: " + remoteMessage.getData());
   }
}

这是我发送的消息Firebase Console

在此处输入图像描述

标签: androidfirebasefirebase-cloud-messaging

解决方案


您需要创建一个通知,然后它将显示在通知托盘上。现在,当您的 on message received 方法被调用时,它只会打印日志。

Intent intent = new Intent();
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)

    .setContentTitle(title)
            .setContentText(message)

            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) 
    getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationID() /* ID of notification */, 
    notificationBuilder.build());

推荐阅读