我有一个 Android 应用程序,它有一个在后台运行的服务,与远程服务器通信并在需要时向用户显示通知。该应用还有一个供用户互动的 Activity 。
其中一个要求是应用程序需要在早上自动启动。在一天结束时,用户可以自由退出应用程序(退出功能会停止服务、释放唤醒锁并让 Android 终止进程)。为了自动重启应用程序,我使用 AlarmManager 和 PendingIntent 安排了一个警报:
//create intent to alert OnStartReceiver when alarm goes off
Intent i = new Intent(context, OnStartReceiver.class);
i.setAction("com.pointtrace.intents.alarm");
i.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION|Intent.FLAG_FROM_BACKGROUND);
//wrap inside PendingIntent so that it can be used from outside
//our application
PendingIntent pi = PendingIntent.getBroadcast(context, 1, i, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Log.d("GXT", "Scheduling alarm action(i)=" + i.getAction());
//set alarm to go off at wake time
alarms.set(AlarmManager.RTC_WAKEUP, getWakeTime(), pi);
OnStartReceiver 类注册接收广播,并在发生警报时重启应用。
除非用户从任务管理器中终止应用程序,否则一切正常。如果应用程序被 Android 操作系统杀死或我调用 System.exit(0) 正常退出;它重新启动正常。但是当它从任务管理器中被杀死时,看起来警报几乎被取消了。
我在 Android 文档中找不到任何暗示警报会被任务管理器取消的内容。关于如何正确设置闹钟,我是不是做错了什么?
我试过删除标志并只使用 0,但没有任何区别。
谢谢。
最佳答案
Quit functionality stops the service, releases the wake lock, and lets Android kill the process
如果你暗示你有一个连续的WakeLock
,除非它只在永久插入的设备上运行,否则你的用户会用鳟鱼打你一巴掌。
此外,Android 可以随时终止进程。不要将 startForeground()
误认为是 Android 永远不会终止您的进程的某种保证。
But when it is killed from Task Manager is looks almost like alarm is getting cancelled.
我不知道“任务管理器”是什么,因为 Android 中没有。如果您指的是“设置”中正在运行的应用程序列表,然后单击“强制停止”,那么是的,这会取消所有未完成的警报并阻止您的应用程序再次运行,直到有人手动启动您的组件之一(例如,用户从启动器启动您的应用程序).
Am I doing something wrong in regards to how to properly set the alarms?
可能不会。强制停止肯定会消除您的警报。
关于应用程序被杀死时 Android 警报取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11658129/