手动终止后重启服务

时间:2014-05-27 06:00:19

标签: android android-service

我想在Android中启动服务,如果它被用户手动杀死,我已经阅读了很多关于这个以及我在服务中使用的内容

我的服务是定期获取当前用户位置及其START_STICKY服务。正如我已经读过whatsapp正在使用GCM再次打开服务,如果它被用户手动杀死,所以我也实现了GCM并启用了服务。

但如果我手动终止了我的服务,那么GCM也会被停止(这是一个明显的原因),所以我认为whatsapp正在使用的{strong> MYTH {{ 1}}重启自己的服务,GCM背后没有魔法。

我已尝试从whtsapp调用startService重新启动该服务,但这也不起作用。

我试图通过使用进程属性将服务作为一个单独的进程运行,但它不起作用

如果服务被用户自己杀死,还是有任何方法可以立即重启服务

注意:我已经知道如果用户手动杀死了服务,如果服务是onDestroy ,操作系统会很快自动重启p>

2 个答案:

答案 0 :(得分:0)

实际上,如果任何用户因为AlarmManager而在非常短的时间内手动停止它,那么任何时候都不会停止应用服务。使用alarmmanager而不是START_STICKY标志。 您的服务在被用户杀死后自动启动。检查链接: http://androidsamplecodes4u.blogspot.in/2012/08/start-service-with-alarm-manager-android.html

答案 1 :(得分:0)

在您的服务中覆盖此方法,希望它能正常工作

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

    //Restart the service once it has been killed android


    AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);

}