我有一个在特定时间触发的BroadcastReceiver (通过AlarmManager)。根据用户设置的首选项,对其进行编程调度。
BroadcastReceiver做到了(简化的和伪代码):
public void onReceive(Context context, Intent intent) {
handler = new Handler();
wifiManager.setWifiEnabled(true);
// Wait a few seconds to activate wifi and get IP
handler.postDelayed(new Runnable() {
void run() {
doTheJob();
}
}, 30000);
}
public void doTheJob() {
doSomethingAndTheOther(); // this starts service: context.startService(i);
wifiManager.setWifiEnabled(false);
}我已经在HTC Desire中使用这个代码好几年了,没有任何问题。此外,没有用户抱怨它不能工作。
然而,我最近买了一台Galaxy S3,它的功能并不像预期的那样好。当我在未来几分钟内设置闹钟(使用已告知的首选项)时,它会按预期工作: BroadcastReceiver唤醒,wifi打开,等待,工作完成,wifi关闭。
但如果我在晚上设置闹钟(例如,3:00:00),它不会:闹钟被触发,wifi被打开……没别的了。这项工作既没有完成,显然wifi在最后也没有关闭。我已经创建了日志并调用了postDelayed(),但从未调用过Runnable.run()。
在调用run()之前,我的BroadcastReceiver进程似乎已经死了。
知道为什么吗?你知道我该怎么避免它吗?
发布于 2013-02-24 16:49:53
BroadcastReceivers总是在使用后立即销毁。我不确定它是否在以前的Android版本中发生了变化,但你永远不应该假设广播接收器的实例会一直存在。它们的目的是立即处理事件,延迟处理应该使用AlarmManager或在服务中发生。
https://stackoverflow.com/questions/15049981
复制相似问题