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

Android中BaseBundle.get(String)及getParcelableExtra过时,如何用类型安全方法?

解决Bundle/Intent中Parcelable获取方法过时的问题

Android API 33及以上版本中,Bundle.get(String)和Intent.getParcelableExtra(String)这类无类型约束的方法已被标记为过时,官方推荐使用带类型参数的类型安全方法替代,既消除警告又能避免运行时类型转换错误。

具体替换方案

  • 从Bundle中获取Bitmap:将(Bitmap) extras.get("data")替换为extras.getParcelable("data", Bitmap.class)
  • 直接从Intent中获取Bitmap:将(Bitmap) data.getParcelableExtra("data")替换为data.getParcelableExtra("data", Bitmap.class)

修改后的完整代码

startActivityForResult = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        // 类型安全获取Bitmap,无需额外强转
                        Bitmap tmp = data.getParcelableExtra("data", Bitmap.class);
                        if (tmp != null) {
                            encodeBitmapAndSaveToFirebase(tmp);
                            imageBtnRotateProfileImage.setVisibility(View.VISIBLE);
                            imageBtnDeleteProfileImage.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
    );

补充说明

带Class<T>参数的重载方法会在编译阶段完成类型校验,省去了手动强制转换的步骤。如果需要兼容API 33以下的设备,只要项目依赖了最新版本的AndroidX Core库,就能正常使用这些方法,无需额外的版本判断逻辑。

内容的提问来源于stack exchange,提问作者robg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 06:22:08