如果我在onStartCommand中返回START_REDELIVER_INTENT,我知道安卓服务会重启
我写了一个服务,并希望在用户关闭最近列表中的应用程序后保持它的活力
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_REDELIVER_INTENT;
}在我的测试之后,如果用户关闭最近列表中的应用程序,我的服务将被终止
由于START_REDELIVER_INTENT,安卓将自动重启服务,但时间太长
有时服务会在20秒内重启,有时重启时间会超过一分钟,如何缩短重启时间?5秒内更好。
发布于 2016-10-26 12:54:10
在您的Service类中使用此代码。当用户清除应用程序时,此重新启动服务。并且您可以将START_STICKY返回给onstartCommand方法。
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent intent2 = new Intent(this.getApplicationContext(), this.getClass());
intent2.setPackage(this.getPackageName());
PendingIntent pendingIntent = PendingIntent.getService((Context)this.getApplicationContext(), (int)1, (Intent)intent2,0);
((AlarmManager)this.getApplicationContext().getSystemService(ALARM_SERVICE)).set(3, 500 + SystemClock.elapsedRealtime(), pendingIntent);
super.onTaskRemoved(rootIntent);
}https://stackoverflow.com/questions/40253112
复制相似问题