我有一个后台服务,即使我的主要活动被杀或处于后台,也会运行很长时间。
问题出在:
在这种情况下,我的服务被终止,无法自动重启。
这是我的服务代码:
public class MyService extends Service {
protected final String TAG = this.getClass().getName();
@Override
public void onCreate() {
super.onCreate();
}
@Override
public final int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStarCommand(): Received id " + startId + ": " + intent);
return START_STICKY;
}
@Override
public final IBinder onBind(Intent intent) {
return m_messenger.getBinder();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service Stopped.");
}
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
super.onTaskRemoved(rootIntent);
}
}