Xamarin Android中Bundle.GetParcelable弃用问题的解决方案
技术百科
聖光之護
发布时间:2025-07-02
浏览: 次 Bundle.GetParcelable弃用背景与原因
随着Android API的不断演进,为了提升代码的类型安全性和健壮性,Android 13 (API 33, Tiramisu) 开始对Bundle类中用于获取Parcelable对象的方法进行了更新。原有的Bundle.GetParcelable(string key)方法被标记为弃用(@deprecated),取而代之的是一个类型更安全的重载方法:Bundle.GetParcelable(string key, Class
弃用旧方法的主要原因在于其缺乏类型推断,返回的是一个通用的Parcelable类型,需要开发者进行强制类型转换,这在运行时可能导致ClassCastException。新方法通过引入Class
旧版代码示例
在API 33之前,典型的Parcelable对象在Activity之间传递和接收的代码如下所示:
发送数据:
// 假设 User 是一个实现了 IParcelable 接口的自定义类
User MyUser = new User("John", "Doe", /* ... 其他属性 ... */);
Intent intent = new Intent(this, typeof(Menu));
Bundle bundlee = new Bundle();
bundlee.PutParcelable("MyUser", MyUser); // 将 User 对象放入 Bundle
intent.PutExtra("TheBundle", bundlee);
StartActivity(intent);接收数据:
Bundle bundlee = Intent.GetBundleExtra("TheBundle");
User MyUser = new User("", "", /* ... 默认值 ... */); // 初始化一个 User 对象
// 旧的弃用方法:需要进行类型转换
MyUser = bundlee.GetParcelable("MyUser") as User;当项目目标框架升级到API 33或更高版本时,bundlee.GetParcelable("MyUser")这一行代码就会出现弃用警告。
新版GetParcelable方法解析
新的Bundle.GetParcelable方法签名如下(Java):
@Nullable publicT getParcelable(@Nullable String key, @NonNull Class clazz) { // ... implementation ... }
其中,clazz参数是关键,它要求传入一个java.lang.Class对象,明确指定期望获取的Parcelable对象的类型。这使得Android系统能够在内部进行更精确的类型检查。
对于Xamarin/C#开发者而言,挑战在于如何将C#中的System.Type对象转换为Java层所需的java.lang.Class对象。
Xamarin/C# 中的解决方案
在Xamarin Android中,Java.Lang.Class.FromType()方法提供了将C# System.Type转换为java.lang.Class的能力。这是解决Bundle.GetParcelable弃用问题的核心。
因此,接收Parcelable对象的代码应修改为:
// 假设 bundlee 已经通过 Intent.GetBundleExtra("TheBundle") 获取
Bundle bundlee = Intent.GetBundleExtra("TheBundle");
// 确保 bundlee 不为 null
if (bundlee != null)
{
// 使用新的 GetParcelable 方法,传入 Java.Lang.Class.FromType(typeof(User))
// 这将 C# 的 User 类型转换为 Java 的 Class 对象
User MyUser = bundlee.GetParcelable("MyUser", Java.Lang.Class.FromType(typeof(User))) as User;
// 检查 MyUser 是否成功获取并进行后续操作
if (MyUser != null)
{
// ... 使用 MyUser 对象 ...
}
}或者,如果你已经有一个该类型的实例,也可以使用其运行时类型:
// 假设 MyUser 已经被初始化为一个 User 类型的实例
User MyUser = new User("", "", /* ... 默认值 ... */);
// 使用实例的运行时类型
MyUser = bundlee.GetParcelable("MyUser", Java.Lang.Class.FromType(MyUser.GetType())) as User;推荐使用typeof(User)形式,因为它在编译时就能确定类型,避免了潜在的运行时类型不匹配问题。
完整示例与注意事项
自定义 User 类(需实现 IParcelable 接口):
using Android.OS;
using Android.Runtime;
using System;
// 确保类标记为 [Parcelable] 并实现 IParcelable
[Parcelable]
public class User : Java.Lang.Object, IParcelable
{
public string FirstName { get; set; }
public string LastName { get; set; }
// ... 其他属性 ...
public User() { } // 无参构造函数,用于反序列化或默认初始化
// 构造函数,用于初始化属性
public User(string firstName, string lastName /* ... 其他参数 ... */)
{
FirstName = firstName;
LastName = lastName;
// ... 初始化其他属性 ...
}
// 实现 IParcelable.DescribeContents()
public int DescribeContents()
{
return 0;
}
// 实现 IParcelable.WriteToParcel() - 将对象写入 Parcel
public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
dest.WriteString(FirstName);
dest.WriteString(LastName);
// ... 写入其他属性 ...
}
// 实现 IParcelable.Creator - 用于从 Parcel 创建对象
[ExportField("CREATOR")]
public static UserCreator InitializeCreator()
{
return new UserCreator();
}
public class UserCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
// 从 Parcel 中读取数据,顺序必须与 WriteToParcel 写入的顺序一致
string firstName = source.ReadString();
string lastName = source.ReadString();
// ... 读取其他属性 ...
return new User(firstName, lastName /* ... 其他参数 ... */);
}
public Java.Lang.Object[] NewArray(int size)
{
return new User[size];
}
}
}发送 Activity (例如 MainActivity.cs):
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
[Activity(Label = "MainActivity", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Button btnNavigate = FindViewById接收 Activity (例如 MenuActivity.cs):
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
[Activity(Label = "MenuActivity")]
public class MenuActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_menu);
TextView tvUserInfo = FindViewById(Resource.Id.tvUserInfo);
Bundle bundle = Intent.GetBundleExtra("TheBundle");
if (bundle != null)
{
// 使用新的 GetParcelable 方法
User receivedUser = bundle.GetParcelab
le("MyUser", Java.Lang.Class.FromType(typeof(User))) as User;
if (receivedUser != null)
{
tvUserInfo.Text = $"User: {receivedUser.FirstName} {receivedUser.LastName}";
}
else
{
tvUserInfo.Text = "Failed to retrieve user data.";
}
}
else
{
tvUserInfo.Text = "No bundle received.";
}
}
} 注意事项:
- IParcelable 实现的正确性: 确保你的自定义类正确实现了IParcelable接口,包括DescribeContents、WriteToParcel以及静态的IParcelableCreator(通过[ExportField("CREATOR")]特性导出)。这是Parcelable机制正常工作的基石。
- setClassLoader(): Android文档中提到,如果Parcelable对象不是Android平台提供的类,可能需要先调用Bundle.SetClassLoader(ClassLoader)。然而,对于大多数自定义的Parcelable实现,Xamarin的运行时通常会自动处理类加载器的问题,因此在实践中,通常不需要显式调用此方法。但了解其存在有助于在遇到特殊类加载问题时进行排查。
- 类型安全: 新的GetParcelable方法强制你在编译时指定类型,这有助于捕获潜在的类型不匹配错误,而不是等到运行时才暴露问题。
- 兼容性: 如果你的应用需要同时支持API 33以下和API 33及以上版本,你可能需要根据Build.VERSION.SdkInt进行条件判断,使用不同的GetParcelable重载。然而,考虑到向前兼容性,直接升级到使用新方法是更推荐的做法,因为新方法在旧版本API上通常也能正常工作(尽管可能不会有弃用警告)。
总结
Bundle.GetParcelable(string)的弃用是Android API演进中提升类型安全性的一个体现。对于Xamarin开发者而言,通过利用Java.Lang.Class.FromType()方法,可以无缝地将C# System.Type映射到Java Class对象,从而适配新的Bundle.GetParcelable(string key, Class
# ai
# 的是
# 是一个
# 这是
# 时就
# 实现了
# 自定义
# 升级到
# 对象
# Java
# String
# class
# c#
# 接口
# typeof
# 类型转换
# 默认值
# 转换为
# 不匹配
# android
# 强制类型转换
# xamarin
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- c++中如何进行二进制文件读写_c++ read与
- Win11怎样激活系统密钥_Win11系统密钥激活
- Win11怎么退出微软账户_切换Win11为本地账
- 如何使用Golang sync.Map实现并发安全
- 如何高效识别并拦截拼接式恶意域名 spam
- 如何在 Go 同包不同文件中正确引用结构体
- mac怎么分屏_MAC双屏显示与分屏操作技巧【指南
- Win11开始菜单打不开_修复Windows 11
- 如何在JavaScript中动态拼接PHP的bas
- Windows 11登录时提示“用户配置文件服务登
- Windows服务启动类型恢复方法_错误修改导致的
- windows如何禁用驱动程序强制签名_windo
- php下载安装选zip还是msi格式_两种安装包对
- MAC如何设置网卡MAC地址克隆_MAC终端修改物
- Win11更新后变慢怎么办_Win11系统更新后卡
- c++中的Tag Dispatching是什么_c
- 如何在Golang中使用闭包_封装变量与函数作用域
- 如何在Golang中实现并发消息队列消费者_Gol
- windows如何测试网速_windows系统网络
- 用Python构建微服务架构实践_FastAPI与
- Win10怎样安装PPT模板_Win10安装PPT
- Win11怎么开启智能存储_Windows11存储
- 用lighttpd能运行php吗_lighttpd
- 如何在Windows中创建新的用户账户?(标准与管
- php订单日志怎么在swoole写_php协程sw
- Win11怎么关闭内容自适应亮度_Windows1
- XAMPP 启动失败(Apache 突然停止)的终
- Win11怎么开启游戏模式_Windows11优化
- PHP的Workerman对架构扩展有啥帮助_应用
- Win11如何关闭小娜Cortana Win11禁
- Windows 10怎么隐藏特定更新补丁_Wind
- Win10怎样卸载DockerDesktop_Wi
- 如何使用Golang实现云原生应用弹性伸缩_自动应
- Windows10怎样设置家长控制_Windows
- 短链接还原php提示内存不足_调整PHP内存限制设
- php订单日志怎么按状态筛选_php筛选不同状态订
- C++中的协变与逆变是什么?C++函数指针与返回类
- 一文教你快速开通网站LOGO图
- Win10如何卸载预装Edge扩展_Win10卸载
- Windows蓝屏错误0x00000018怎么处理
- Windows怎样关闭开始菜单推荐广告_Windo
- 如何使用Golang实现Web表单数据绑定_自动映
- Win11视频默认播放器怎么改_Win11关联第三
- Golang如何避免指针逃逸_Golang逃逸分析
- 如何使用 Python 合并文件夹内多个 Exce
- Golang如何实现基本的用户注册_Golang用
- Win11时间怎么同步到原子钟 Win11高精度时
- Python变量绑定机制_引用模型解析【教程】
- Windows 10怎么把任务栏放在屏幕上方_Wi
- c++的STL算法库find怎么用 在容器中查找指

le("MyUser", Java.Lang.Class.FromType(typeof(User))) as User;
if (receivedUser != null)
{
tvUserInfo.Text = $"User: {receivedUser.FirstName} {receivedUser.LastName}";
}
else
{
tvUserInfo.Text = "Failed to retrieve user data.";
}
}
else
{
tvUserInfo.Text = "No bundle received.";
}
}
}
QQ客服