我应该在Android服务的onDestroy方法中调用onCreate方法吗? [英] Should i call onCreate method in onDestroy method in android service?

查看:107
本文介绍了我应该在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);
}

这篇关于我应该在Android服务的onDestroy方法中调用onCreate方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆