阅读文档,看起来 BroadcastReceiver 是在不同的进程上执行的,但我不是 100% 确定(BroadcastReceiver 生命周期)
当前正在执行 BroadcastReceiver(即当前正在其 onReceive(Context, Intent) 方法中运行代码)的进程被认为是前台进程
这就是说,我不认为从 onReceive 访问活动是安全的,因为它是一个不同的过程,它可能会崩溃。
考虑到 Activity 也可以充当广播接收器,但您必须控制它在其生命周期中何时主动侦听事件。这样,你就可以订阅 onResume (代码提取自 ZXing 项目)
public void onResume(){
activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
[...]
}
public void onPause() {
[...]
activity.unregisterReceiver(powerStatusReceiver);
}
并且您将 BroadcastReceiver 定义为公共类中的私有类
final class InactivityTimer {
[onResume, onPause, rest of the stuff ...]
private final class PowerStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
// 0 indicates that we're on battery
// In Android 2.0+, use BatteryManager.EXTRA_PLUGGED
int batteryPlugged = intent.getIntExtra("plugged", -1);
if (batteryPlugged > 0) {
InactivityTimer.this.cancel();
}
}
}
}
}
So, the BroadcastReceiver should always persist the new markers (through a Service, never inside the onReceive) AND it should notify a potentially active MapActivity that new markers have been added, which will be listening if it's active.
Or, even easier, the Activity and the BroadcastReceiver listen for the same SMS Intent. While the latter persists it, the first updates the map, tho I'm just guessing what I would try.