在我的应用程序中,我在后台使用基于位置的服务。所以我需要在它被销毁时重新启动我的服务。
但我在 logcat 中收到了这条消息
ProcessRecord{320afaf6 20614:com.odoo.crm:my_odoo_gps_service/u0a391} 的虚假死亡,20614 的 curProc:null
我的服务onTaskRemoved
@Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
Intent restartServiceIntent = new Intent(App.getAppContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent =
PendingIntent.getService(App.getAppContext(), 1, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService =
(AlarmManager) App.getAppContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
}
我的服务onDestroy
@Override
public void onDestroy() {
System.out.println("destroy service");
super.onDestroy();
wakeLock.release();
}
我的服务 onStartCommand
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
我不知道错误是什么。我在 google 和 stackoverflow 中都进行了搜索。 他们都提到了 Service.START_STICKY。但我已经用过了。
相同的服务重启在 KitKat 中有效,但有一些延迟(~5 分钟)。
感谢任何帮助。
最佳答案
您可以使用 BroadcasteReceiver
重新启动它,它处理从您的服务的 onDestroy()
发送的广播。
如何做到这一点:
StickyService.java
public class StickyService extends Service
{
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("IWillStartAuto"));
}
@Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("IWillStartAuto"));
}
}
RestartServiceReceiver.java
public class RestartServiceReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context.getApplicationContext(), StickyService.class));
}
}
在 list 文件中声明组件:
<service android:name=".StickyService" >
</service>
<receiver android:name=".RestartServiceReceiver" >
<intent-filter>
<action android:name="IWillStartAuto" >
</action>
</intent-filter>
</receiver>
希望对您有所帮助。
关于Android 服务不会在 Lollipop 中重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35747624/