如何在被“高级任务杀手”等应用程序杀死后重启服务?

时间:2013-12-13 00:30:02

标签: android service restart

我有一个“扩展服务”的公共类,这个服务是使用startService(...)从一个活动启动的。但是在我使用Advanced Task Killer之后,该服务被终止并且再也没有重新启动。

我注意到Facebook Messenger Android App之类的某些应用即使在从Advanced Task Killer中删除后也会自动重启... facebook / twitter应用程序是如何做到的?

enter image description here

3 个答案:

答案 0 :(得分:12)

Android系统或用户可以随时终止服务。因此,如果要确保始终运行某些内容,可以通过AlarmManager类安排定期重新启动。以下代码演示了如何执行此操作。

Calendar cal = Calendar.getInstance();

Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every minute
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent); 

您可以在用户启动应用程序时运行此代码(即在第一个活动的oncreate中),但是您必须检查它是否已经完成,所以如果您创建广播接收器可能会比启动更好系统重启时此代码。

答案 1 :(得分:10)

如果您想在被其他进程杀死后自动重启服务,可以在服务中使用以下常量,

@Override
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_STICKY;
}

您可以在START_STICKY&中找到更多信息。 START_NON_STICKY at,

START_STICKY and START_NOT_STICKY

另请提供您的代码以获得更具体的答案。

答案 2 :(得分:2)

在服务返回START_STICKY

中创建onStartCommand()
  /**
     * Constant to return from {@link #onStartCommand}: if this service's
     * process is killed while it is started (after returning from
     * {@link #onStartCommand}), then leave it in the started state but
     * don't retain this delivered intent.  Later the system will try to
     * re-create the service.  Because it is in the started state, it will
     * guarantee to call {@link #onStartCommand} after creating the new
     * service instance; if there are not any pending start commands to be
     * delivered to the service, it will be called with a null intent
     * object, so you must take care to check for this.
     * 
     * <p>This mode makes sense for things that will be explicitly started
     * and stopped to run for arbitrary periods of time, such as a service
     * performing background music playback.
     */
    public static final int START_STICKY = 1;