我应该在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);
}