我应该在Android服务的onDestroy方法中调用onCreate方法吗?

问题描述:

我想在销毁服务时再次启动它.

I want to startservice again when it was destroyed.

@Override
    public void onDestroy() {
        super.onDestroy();
        onCreate();
    }

您不应这样做.这不会做任何事情.要重启服务,您应该在 onTaskRemove()上重启它,如下所示.

You should not do this . This is not going to do anything. To restart a service you should restart it on onTaskRemove() like below.

@Override
public void onTaskRemoved(Intent rootIntent) {
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}