尽管已实现了所有必要的添加,但我在向 Android 应用程序发送通知时遇到了问题。
我开发了一个 WebView 应用程序,并遵循在各种互联网资源上找到的常见做法来实现通知。首先,在
MainActivity.java
中,在 onCreate
方法中,我调用了:
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
System.out.println("Fetching FCM registration token failed");
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
}
});
此外,我对
MyFirebaseMessagingService.java
文件进行了必要的添加,如各种在线资源中所述:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
System.out.println("From: " + remoteMessage.getFrom());
if (remoteMessage.getNotification() != null) {
System.out.println("Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
}
private void sendNotification(String from,String body){
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
}
});
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
String channelId = "notification";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle("TeknoFore")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
我也在
AndroidManifest.xml
中声明了该服务如下:
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
此外,我确保授予了
POST_NOTIFICATIONS
权限,并将 google-services.json
文件放置在应用程序目录中。然而,尽管采取了这些步骤,但通过令牌发送的测试通知和直接发送到应用程序的通知都没有被接收到。
什么可能导致此问题?如何解决?任何见解将不胜感激。谢谢你。
尝试改变
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
到
notificationManager.notify(1 /* ID of notification */, notificationBuilder.build());
在其中一个示例中,我读到 notificationId 应该为正值