Android service 自动重启

当Android的service被停止(内存不够、被其他app杀掉)的时候,加入以下代码到你的service里,就可以马上重新启动了。

@Override
public void onDestroy() {
  super.onDestroy();
  // Restart service in 500 ms
  ((AlarmManager) getSystemService(Context.ALARM_SERVICE))
  .set(AlarmManager.RTC,
    System.currentTimeMillis() + 500,
    PendingIntent.getService(this, 3, new Intent(this, TaskService.class), 0));
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注