我有一个 Android 服务负责在特定时间点触发通知。我为此使用了 android.OS.CountdownTimer。一个 Activity 创建并启动服务。如果手机已锁定,则显示 1 分钟内的通知。永远不会显示晚得多的通知。当 Activity 处于暂停状态时,服务与 Activity 解除绑定(bind)。
只要手机没有锁定,就会生成通知,即使 Activity 已停止并与服务解除绑定(bind)。
在我看来,该服务已停止/终止。当我使应用程序可调试并在目标上对其进行调试时,它工作正常,当 Activity 停止且服务未绑定(bind)时也是如此。
该应用程序是为 v1.5 开发的,在 Galaxy S 2.2 上运行。
服务启动如下图
serviceIntent = new Intent().setAction("com.mytest.MyService");
startService(serviceIntent);
bindService(new Intent(context,
MyService.class), mConnection, 0 /*Context.BIND_AUTO_CREATE*/);
最佳答案
I have an Android service that's responsible for firing notifications at certain points in time. I use an android.OS.CountdownTimer for this.
请不要这样做。请使用 AlarmManager
和 IntentService
,这样您就不会一直运行服务。用户将使用任务 killer 或“设置”应用程序中的“管理服务”屏幕终止您的服务。 Android 将停止您的服务。您最好使用符合用户和平台期望的架构 (AlarmManager
/IntentService
)。
关于Android 服务意外终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4148163/