問題:
項(xiàng)目中有個(gè)鎖屏service,間隔30秒屏幕黑屏,向右滑動(dòng)解鎖,防止誤操作的,最近客戶反饋崩潰次數(shù)有點(diǎn)多
查看崩潰日志如下
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)以后后臺服務(wù)做了限制
解決:
1,在manifests.xml加入權(quán)限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
2,啟動(dòng)服務(wù)startService改動(dòng)
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;
}
//啟動(dòng)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,開啟通知,否則報(bào)錯(cuò)如下:文章來源:http://www.zghlxwxcb.cn/news/detail-619413.html
Context.startForegroundService() did not then call Service.startForeground()
意思是5秒內(nèi)必須調(diào)用startForeground,可參考文章來源地址http://www.zghlxwxcb.cn/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("鎖屏服務(wù)中...")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.icon_logo).build()
startForeground(2, notification)
}
}
//關(guān)閉通知
private fun stopServiceForeground() {
stopForeground(true)
}
override fun onDestroy() {
stopServiceForeground()
super.onDestroy()
}
到了這里,關(guān)于Not allowed to start service Intent app is in background uid UidRecord的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!