You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:16:11