在Android Oreo中,FCM(Firebase Cloud Messaging)推送通知需要做一些额外的适配工作。以下是一个解决Android Oreo中FCM推送通知问题的示例代码:
default_channel
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
public class NotificationHelper {
private static final String CHANNEL_ID = "default_channel";
private static final String CHANNEL_NAME = "Default Channel";
private static final String CHANNEL_DESCRIPTION = "Default notification channel";
public static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESCRIPTION);
notificationManager.createNotificationChannel(channel);
}
}
}
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// 处理收到的消息
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
private void showNotification(String title, String body) {
NotificationHelper.createNotificationChannel(this);
// 创建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationHelper.CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());
}
}
这样,在Android Oreo中,你就能够正确地显示FCM推送的通知了。请记得将代码中的图标和通知内容替换为你自己的内容。