本文主要是介绍android 8.0 服务启动报错Fatal Exception: java.lang.IllegalStateException Not allowed to start service Inte,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Fatal Exception: java.lang.IllegalStateException Not allowed to start service Intent { act=com.xxx.xxx.xxx pkg=com.xxx.xxx (has extras) }: app is in background uid UidRecord{1cbd9ed u0a1967 CEM idle procs:1 seq(0,0,0)}
我们需要使用startForegroundService()来代替之前大方法,但是要在Sevice中调用startForeground()方法
但是我原先的代码是api 大于18 的判断其中 ,已经使用了startForeground()(后来发现与 android 8.0 有关)
//如果API大于18,需要弹出一个可见通知if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){Notification.Builder builder = new Notification.Builder(this);builder.setSmallIcon(R.mipmap.ic_launcher);builder.setContentTitle("KeepAppAlive");builder.setContentText("DaemonService is runing...");startForeground(NOTICE_ID,builder.build());// 如果觉得常驻通知栏体验不好// 可以通过启动CancelNoticeService,将通知移除,oom_adj值不变Intent intent = new Intent(this,MainActivity.class);startService(intent);}else{startForeground(NOTICE_ID,new Notification());}
现在由于android 8.0的服务我们更改为api大于26
但是这样的话可能报通知的错误
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=default defaults=0x1 flags=0x40 color=0x00000000 vis=PRIVATE)
我们更改通知,使其适配Android 8.0
使用的常量:
public static final int NOTICE_ID = 100; private static final String CHANNEL_ONE_ID = "channel"; private static final CharSequence CHANNEL_ONE_NAME = "channelName";
我们需要更改通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME,NotificationManager.IMPORTANCE_MIN);notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯notificationChannel.setShowBadge(false);//是否显示角标notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);NotificationManager notificationManager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);notificationManager.createNotificationChannel(notificationChannel);Notification.Builder builder=new Notification.Builder(getApplicationContext(),CHANNEL_ONE_ID);builder.setSmallIcon(R.mipmap.ic_launcher);builder.setAutoCancel(true);builder.setChannelId(CHANNEL_ONE_ID);builder.setWhen(System.currentTimeMillis());builder.setContentTitle("题目闹钟");builder.setContentText("内容闹钟");builder.setNumber(3);startForeground(NOTICE_ID, builder.build());// 如果觉得常驻通知栏体验不好// 可以通过启动CancelNoticeService,将通知移除,oom_adj值不变Intent intent = new Intent(this, MainActivity.class);startService(intent);} else {startForeground(NOTICE_ID, new Notification());}
参考:https://blog.csdn.net/chw12341/article/details/82291108
https://blog.csdn.net/qq_32072451/article/details/82016901
这篇关于android 8.0 服务启动报错Fatal Exception: java.lang.IllegalStateException Not allowed to start service Inte的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!