1.添加权限<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
2.添加版本判断
private Socket_BackService socketservice;
socketservice = new Intent(this, Socket_BackService.class);
//适配8.0 无法背地开启服务的异常
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {startForegroundService(socketservice);
}else {startService(socketservice);
}
3.//在Socket_BackService 中添加以下代码
public static final String CHANNEL_ID_STRING = "service_chatroom"; onCreate()添加以下代码
//适配8.0serviceNotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);NotificationChannel mChannel = null;if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {mChannel = new NotificationChannel(CHANNEL_ID_STRING, getString(R.string.app_name),NotificationManager.IMPORTANCE_LOW);notificationManager.createNotificationChannel(mChannel);Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();startForeground(1, notification);}
运行试试效果吧!