在Android 8.0(API级别26)及更高版本中,引入了后台限制,即限制应用在后台启动服务。为了解决这个问题,需要在调用Context.startForegroundService()启动服务后,立即调用Service.startForeground()。
以下是一个示例代码,演示了如何正确调用Context.startForegroundService()和Service.startForeground():
在Activity中启动服务:
Intent serviceIntent = new Intent(this, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
} else {
startService(serviceIntent);
}
在Service中调用startForeground()和stopForeground():
public class MyService extends Service {
private static final int NOTIFICATION_ID = 1;
@Override
public void onCreate() {
super.onCreate();
// 创建并设置通知
Notification notification = createNotification();
startForeground(NOTIFICATION_ID, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 处理服务逻辑
// ...
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
private Notification createNotification() {
// 创建并返回通知
// ...
}
}
在上面的示例中,当调用Context.startForegroundService()启动服务时,会根据设备的API级别选择不同的启动方法。在Service的onCreate()方法中,会创建并设置一个通知,然后调用Service.startForeground()方法将服务设置为前台服务。在Service的onDestroy()方法中,会调用stopForeground(true)方法,将服务从前台移除。
通过这种方式,可以解决ANR: Context.startForegroundService()没有调用Service.startForeground(),对用户不可见的问题。
上一篇:ANR-原因:空指针解引用