处理步骤:
-
权限问题 :
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
-
Android 8.0以上需要Notification需要设置个Channel
下面2处都需要注意设置channelId
2.1: 接收通知
Notification.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (!UmengMessageHandler.isChannelSet) { UmengMessageHandler.isChannelSet = true; NotificationChannel chan = new NotificationChannel(UmengMessageHandler.PRIMARY_CHANNEL, PushAgent.getInstance(context).getNotificationChannelName(), NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager != null) { manager.createNotificationChannel(chan); } } builder = new Notification.Builder(context, UmengMessageHandler.PRIMARY_CHANNEL); } else { builder = new Notification.Builder(context); }
2.2: 服务 oncreate
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notification = new Notification.Builder(this, UmengMessageHandler.PRIMARY_CHANNEL).getNotification(); notification.flags |= Notification.FLAG_NO_CLEAR; startForeground(1, notification); }
服务启动注意:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, SocketService.class));
} else {
context.startService(new Intent(context, SocketService.class));
}