Caused by: : Permission Denial: startForeground from pid=12394, uid=10302 requires .FOREGROUND_SERVICE
翻译:原因::权限拒绝:StartForeground from PID=12394,ULD=10302需要
Android在8.0开始限制后台服务,启动后台服务需要设置通知栏,使服务变成前台服务。同时在Android 9.0开始注册权限.FOREGROUND_SERVICE,并授权权限。
从8.0开始启动服务需要进行判断出来如下:
/**
* Android 8.0及以后,启动服务的形式已经变了
*/
private void startService(Context context) {
Intent intent = new Intent(context, );
if (.SDK_INT >= Build.VERSION_CODES.O) {
(intent);
} else {
(intent);
}
}
同时在Service的onCreate()方法里设置通知栏如下:
@Override
public void onCreate() {
();
if (.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("xxx", "xxx", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager == null)
return;
(channel);
Notification notification = new (this, "xxx")
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_SERVICE)
.setOngoing(true)
.setPriority(NotificationManager.IMPORTANCE_LOW)
.build();
}
}