应用程序停止时,IntentService将被终止

时间:2013-09-26 21:12:09

标签: android android-service

我有这个IntentService:

public class ServiceUpdateNewResults extends IntentService{ 

private void setAlarmToCheckUpdates() {
    Calendar calendar = Calendar.getInstance();

    //calendar.add(Calendar.DAY_OF_YEAR, 1); //dema
    //calendar.set(Calendar.HOUR_OF_DAY, 22); //a les 10
    calendar.add(Calendar.SECOND, 20);

    Intent myIntent = new Intent(this.getApplicationContext(), ReceiverCheckUpdates.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent,0);
    AlarmManager alarmManager = (AlarmManager)this.getApplicationContext().getSystemService(this.getApplicationContext().ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}

public ServiceUpdateNewResults() {
    super("ServiceUpdateNewResults");
}

@Override
protected void onHandleIntent(Intent intent) {
    //fem les coses.
    //Toast.makeText(this.getApplicationContext(), "holaa", Toast.LENGTH_LONG).show();
    setAlarmToCheckUpdates();

    Log.d("debugging","hello");
}

}

这是每隔20秒调用一次BroadCastReceiver,最终调用此服务,这将“永远”发生。 (将来它将是1天,而不是20秒)。

这是接收者:

public class ReceiverCheckUpdates extends BroadcastReceiver{
Context context;
@Override
public void onReceive(Context context, Intent intent){
    this.context = context;
    Intent service1 = new Intent(context, ServiceUpdateNewResults.class);
    context.startService(service1);

}
}

这是完美的工作,但如果我从Android设置停止应用程序,该服务也会停止。我想避免这种情况。我希望如果应用程序关闭,服务应该继续工作。

有可能吗? 实际上,什么时候服务被杀?

2 个答案:

答案 0 :(得分:2)

  

如果我从Android设置停止该应用,该服务也会停止

如果“停止Android设置中的应用”,则表示您按下“强制停止”按钮,您的应用将无法再次运行,直到手动运行您的某个组件(例如,用户启动您的活动)。更具体地说,在这种情况下,您的警报是未计划的。

  

我想避免这种情况。

然后不要按“强制停止”按钮。

  

我希望如果应用程序关闭,服务应该继续工作。

在任何非“强制停止”场景中,警报将继续发射(至少在设备入睡之前,考虑到您当前的实施情况)。

答案 1 :(得分:1)

IntentService是您应用的一部分。如果系统销毁您的应用程序,它将破坏IntentService。您可以通过将IntentService置于单独的进程中来减少发生这种情况的可能性,但是您无法阻止系统销毁IntentService。你可以使系统不太可能破坏服务;要做到这一点,你使用“前台”服务。但是,除非你真的需要,否则你应该避免这样做。此外,您不能拥有前台IntentService,因此您必须添加自己的后台Handler和HandlerThread。

相关问题