从ForegroundService传ArrayList<LatLng>到MainActivity,广播Bundle为空求助
问题分析与修复方案
你的问题核心在于广播接收方的数据解析逻辑错误,同时发送方代码可以进一步简化,具体问题和修复步骤如下:
1. 接收方的关键错误
在DataBroadcastReceiver的onReceive方法中,你错误地尝试从intent.getExtras()里再获取一个Parcelable类型的Bundle,但实际上发送方是把ArrayList<LatLng>直接放在了Intent的extras Bundle中,并没有嵌套另一个Bundle,这导致你拿到的是null值。
错误代码片段:
Bundle bundle = intent.getExtras().getParcelable(StaticFields.STATIC_BROADCAST_ACTION);
2. 修复后的完整代码
简化后的ForegroundService发送代码
无需额外创建Bundle,直接使用Intent的putParcelableArrayListExtra方法传递数据更简洁:
private void sendBroadcastToMapsActivity(ArrayList<LatLng> polylinePoints) { Intent intent = new Intent(); intent.setAction(StaticFields.STATIC_BROADCAST_ACTION); // 直接将ArrayList放入Intent,无需嵌套Bundle intent.putParcelableArrayListExtra(StaticFields.STATIC_BROADCAST_EXTRA_KEY, polylinePoints); getApplicationContext().sendBroadcast(intent); }
建议:将广播action和数据key分开定义(比如新增STATIC_BROADCAST_EXTRA_KEY常量),避免action和数据标识混淆。
修复后的MainActivity广播接收代码
private class DataBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d("DataBroadcastReceiver: ", action); // 直接从Intent中获取ArrayList,无需嵌套Bundle ArrayList<LatLng> polylinepoints = intent.getParcelableArrayListExtra(StaticFields.STATIC_BROADCAST_EXTRA_KEY); if(polylinepoints != null) { for (LatLng point : polylinepoints) { Log.d("Test: ", String.valueOf(point)); } } } }
3. 额外注意事项
- 确认
LatLng是Parcelable类型(Google Maps的LatLng已默认实现Parcelable,无需额外处理)。 - 若targetSdkVersion >=26,静态广播会受系统限制,建议改用LocalBroadcastManager、LiveData或PendingIntent等更适配的组件通信方式。
- 记得在MainActivity中正确注册/注销广播接收器,避免内存泄漏:
@Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(StaticFields.STATIC_BROADCAST_ACTION); registerReceiver(new DataBroadcastReceiver(), filter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(new DataBroadcastReceiver()); }
内容的提问来源于stack exchange,提问作者Bernd
相关产品推荐
相关产品推荐

