关闭应用后Android闹钟取消 [英] Android alarm is cancelled after closing the application

查看:30
本文介绍了关闭应用后Android闹钟取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 AlarmManager 的问题,我设置了用于安排重复警报的代码,并且在我运行应用程序后,警报运行良好.即使我点击主页按钮(并且应用程序已暂停),警报仍会按其间隔运行.

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?

代码如下 - 该方法由 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;
 }

接收方代码:

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.

这篇关于关闭应用后Android闹钟取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆