Should i call onCreate method in onDestroy method in android service?

自闭症网瘾萝莉.ら 提交于 2019-12-02 13:07:03

问题


I want to startservice again when it was destroyed.

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

回答1:


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);
}


来源:https://stackoverflow.com/questions/47587720/should-i-call-oncreate-method-in-ondestroy-method-in-android-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!