我想在手机上接收FCM通知。我正在使用下面的代码。现在我的问题是,当我在android oreo上运行并且该应用程序在前台运行时,我没有收到消息(但是在android 7上,它可以正常工作!)。我必须进行哪些更改才能使其正常工作?后台以及该应用被终止时在两个操作系统上均可使用。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
//if the message contains data payload
//It is a map of custom keyvalues
//we can read it easily
if(remoteMessage.getData() != null){
sendNotification(remoteMessage);
}
}
private void sendNotification(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "TestID";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
@SuppressLint("WrongConstant")
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.app_icon)
.setTicker("Ticker")
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info");
notificationManager.notify(1,notificationBuilder.build());
}
}
谢谢!