问题:
项目中有个锁屏service,间隔30秒屏幕黑屏,向右滑动解锁,防止误操作的,最近客户反馈崩溃次数有点多
查看崩溃日志如下
java.lang.IllegalStateException
Not allowed to start service Intent { xxx.xxxService }: app is in background uid UidRecord{91b7553 u0a119 CAC bg:+21m20s281ms idle procs:2 seq(0,0,0)}
xxx(xxx:124)
分析:
android 8.0(O)以后后台服务做了限制
解决:
1,在manifests.xml加入权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
2,启动服务startService改动
public static boolean isServiceRunning(Context ctx, final String className) {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> info = am.getRunningServices(200);
if (info == null || info.size() == 0) return false;
for (ActivityManager.RunningServiceInfo aInfo : info) {
if (className.equals(aInfo.service.getClassName())) return true;
}
return false;
}
//启动service
public static void startService(Context ctx, Class<?> cls) {
if (!isServiceRunning(ctx, cls.getName())) {
Intent intent = new Intent(ctx, cls);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ctx.startForegroundService(intent);
} else {
ctx.startService(intent);
}
}
}
3,开启通知,否则报错如下:文章来源:https://www.toymoban.com/news/detail-619413.html
Context.startForegroundService() did not then call Service.startForeground()
意思是5秒内必须调用startForeground,可参考文章来源地址https://www.toymoban.com/news/detail-619413.html
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
startServiceForeground()
}
return START_STICKY
}
//开启通知
@SuppressLint("NewApi")
private fun startServiceForeground() {
val ns: String = Context.NOTIFICATION_SERVICE
val nm: NotificationManager = getSystemService(ns) as NotificationManager
var nc: NotificationChannel? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
nc = NotificationChannel(
"CoverService", "锁屏",
NotificationManager.IMPORTANCE_LOW
)
nm.createNotificationChannel(nc);
val notification = Notification.Builder(
applicationContext, "CoverService"
).setContentTitle("锁屏服务中...")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.icon_logo).build()
startForeground(2, notification)
}
}
//关闭通知
private fun stopServiceForeground() {
stopForeground(true)
}
override fun onDestroy() {
stopServiceForeground()
super.onDestroy()
}
到了这里,关于Not allowed to start service Intent app is in background uid UidRecord的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!