android - 在KitKat中杀死后服务没有重新启动

时间:2016-09-29 17:11:55

标签: android service

每当我关闭应用程序时,我的服务都无法在KitKat设备上重新启动。请注意,我使用START_STICKY标志。

这是我的服务

@Override
public void onCreate(){
    super.onCreate();
    Log.i("Script", "onCreate()");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    this.context = this;
    Log.i("Script", "flags: "+flags);
    Log.i("Script", "startId: "+startId);
    Log.e("active","active");

    return START_STICKY;
}

在清单中

 <service
        android:name=".TimerService"
        android:enabled="true"
        android:exported="false"
        android:stopWithTask="false"
        >
 </service>

在Lollipop和Marshmallow设备上,我使用 JOB SCHEDULER 并且工作正常。

任何人都知道如何修复它?

1 个答案:

答案 0 :(得分:0)

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);
    Objects.requireNonNull(alarmService).set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);