当应用程序进入后台(通过按下Home键),当屏幕关闭后,Android M (6.0)手机上的后台服务会在15-20分钟后停止。尽管在Lollipop(5.0)手机上正常运行。
根据您在评论中提到的,您已经将服务设为START_STICKY,但是在后台它在Android Marshmallow设备上无法运行。
在注册服务的位置使用Alarmmanager,如下所示:
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,ServiceStarter.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1545, intent, 0);
alarmMgr.set(AlarmManager.RTC,
System.currentTimeMillis() + 5000, alarmIntent);
然后在ServiceStarter广播接收器中执行以下操作...
public class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!ConstantData.isServiceRunning(YourService.class , context)){ //check service is running or not
context.startService(new Intent(context , YourService.class));
}
else{
Log.e("service-->>" , "service already running");
}
try {
//set alarm for next 5 seconds...this will set alarm for every next 5 seconds
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent2 = new Intent(context, ServiceStarter.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1545, intent2, 0);
alarmMgr.set(AlarmManager.RTC,
System.currentTimeMillis() + 5000, alarmIntent);
} catch (Exception e) {
}
}
}
ConstantData.isServiceRunning() 方法:
"public static boolean isServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
BroadcastReceiver
调用context.startService
将在Android 8及更高版本上导致IllegalStateException
。更好的解决方案很大程度上取决于您想要实现什么,现在无法再让自己的服务一直在后台运行了。 - Sander
START_STICKY
。即使由于内存不足或其他任何原因而被操作系统停止,它也会重新启动您的服务。 - Jaydip Kalkani