关闭应用程序后,Android的警报被取消

关闭应用程序后,Android的警报被取消

问题描述:

我有AlarmManager一个问题,我设置了code调度重复报警,我运行该应用程序后,警报正常运行。即使我点击主页按钮(和应用程序暂停),报警仍运行在它的时间间隔。

I have a problem with AlarmManager, I set the code for scheduling a repeating alarm and after I run the application, the alarm runs fine. Even if I click on Home button (and the application is paused), the alarm still runs on its interval.

现在的问题是,如果我打开任务管理器,强行关闭应用程序,然后报警运行停止。

The problem is if I open the Task Manager and force close the application, then the alarm stops from running.

这是一个正常的行为,有没有办法避免这一点,并关闭应用程序后仍保持报警运行?

Is this a normal behavior, is there any way to avoid this and keep the alarm running after closing the application?

在code低于 - 该方法由一个ApplicationContext类的onCreate()

The code is below - the method is called by the ApplicationContext class, onCreate().

 private void scheduleAlarm() {
  if (alarmScheduled == true) { return; } // we only need to schedule once.

  int alarmInterval = Def.pref(getApplicationContext()).getInt("alarmInterval", 30);

  final Intent intent = new Intent(getApplicationContext(), CollectorAlarmReceiver.class);
  final PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

  AlarmManager alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

  alarmMgr.cancel(pending); // cancel others.

  alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+1000,
    alarmInterval*1000, pending);

  Def.log(TAG,"scheduleAlarm(): alarm scheduled, interval: "+alarmInterval+" seconds");
  alarmScheduled = true;
 }

接收器code:

Receiver code:

public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "CollectorAlarmReceiver invoked, starting CollectorService in background");

    context.startService(new Intent(context, CollectorService.class));

    Intent collectorService = new Intent(context,CollectorService.class);
    collectorService.putExtra("action", CollectorService.ACTION_BACKGROUND_REQUEST_MESSAGES);

    context.sendBroadcast(collectorService);
}

谢谢!

这是正常的行为。如果用户自行强制停止应用程序了,那么就应该停止。否则,要创建像应用程序中的病毒。

This is normal behaviour. If the user voluntarily force stop the applicaiton, then it should be stopped. Else, you are creating a virus like application.

如果你真正想要的,你可以写它监视,如果您的其他服务正在运行,如果一个服务没有运行运行服务的其他服务。但是,这将是另一个应用程序,(你希望)使用任务管理器的用户不会杀了这个程序。

If you really want, you could write another service which monitors if your other service is running and runs the service if the one is not running. But this will be another application and (you hope) the user wont kill this app using task manager.

就个人而言,我不会担心。如果用户停止了,他们想阻止它。不要骚扰用户。

Personally, I wouldn't worry. If the user stopped it, they wanted to stop it. Don't annoy the user.