当前位置: 代码迷 >> 综合 >> android 8.1 Not allowed to start service Intent 无法后台开启服务的异常(8.0以上系统)
  详细解决方案

android 8.1 Not allowed to start service Intent 无法后台开启服务的异常(8.0以上系统)

热度:23   发布时间:2023-10-20 14:31:39.0
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);}

运行试试效果吧!

 

  相关解决方案