我是靠谱客的博主 轻松含羞草,这篇文章主要介绍android 8.1 Not allowed to start service Intent 无法后台开启服务的异常(8.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.0service
NotificationManager 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);
}

运行试试效果吧!

 

最后

以上就是轻松含羞草最近收集整理的关于android 8.1 Not allowed to start service Intent 无法后台开启服务的异常(8.0以上系统)的全部内容,更多相关android内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部