Android getParcelableExtra已弃用

i7uaboj4  于 2023-04-18  发布在  Android
关注(0)|答案(5)|浏览(1076)

我通过Intent与Parcelable传递数据并使用getParcelableExtra接收。然而getParcelableExtra似乎已弃用,我如何修复此代码中的弃用警告?或者,是否有其他选项可以做到这一点?我使用compileSdkVersion 33。
代码片段:

var data = intent.getParcelableExtra("data")
5jvtdoz2

5jvtdoz21#

下面是我为BundleIntent使用的两种扩展方法:

inline fun <reified T : Parcelable> Intent.parcelable(key: String): T? = when {
  SDK_INT >= 33 -> getParcelableExtra(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelableExtra(key) as? T
}

inline fun <reified T : Parcelable> Bundle.parcelable(key: String): T? = when {
  SDK_INT >= 33 -> getParcelable(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelable(key) as? T
}

我也是requested this to be added to the support library
如果你需要ArrayList支持,有:

inline fun <reified T : Parcelable> Bundle.parcelableArrayList(key: String): ArrayList<T>? = when {
  SDK_INT >= 33 -> getParcelableArrayList(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelableArrayList(key)
}

inline fun <reified T : Parcelable> Intent.parcelableArrayList(key: String): ArrayList<T>? = when {
  SDK_INT >= 33 -> getParcelableArrayListExtra(key, T::class.java)
  else -> @Suppress("DEPRECATION") getParcelableArrayListExtra(key)
}
odopli94

odopli942#

现在,我们需要使用getParcelableExtra()和添加到API 33的类型安全类
Kotlin的示例代码

val userData = if (VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  intent.getParcelableExtra("DATA", User::class.java)
} else {
  intent.getParcelableExtra<User>("DATA")
}

Java的示例代码

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  user = getIntent().getParcelableExtra("data", User.class);
} else {
  user = getIntent().getParcelableExtra("data");
}
nnsrf1az

nnsrf1az3#

如官方文档所述,getParcelableExtra在API级别33中被弃用。
因此,请检查API LEVEL是否〉= 33或更改方法,

...

if (Build.VERSION.SDK_INT >= 33) { // TIRAMISU
    data = intent.getParcelableExtra (String name, Class<T> clazz)
}else{
    data = intent.getParcelableExtra("")
}

下面是一个使用android.bluetooth.BluetoothDevice的示例

...
val device = if (Build.VERSION.SDK_INT >= 33){ // TIRAMISU
    intent.getParcelableArrayExtra(
        BluetoothDevice.EXTRA_NAME,
        BluetoothDevice::class.java
    )
}else{
    intent.getParcelableExtra(BluetoothDevice.EXTRA_NAME)
}
oug3syen

oug3syen4#

例如,在Java中:

UsbDevice device;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2) { // TIRAMISU onwards
    device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice.class);
} else {
    device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
}

这仍然需要@SuppressWarnings({"deprecation", "RedundantSuppression"})

sbtkgmzw

sbtkgmzw5#

androidx.core:core-ktx:1.10.0-rc 01提供了IntentCompatBundleCompat
检索android.bluetooth.BluetoothDevice对象的示例:

IntentCompat.getParcelableExtra(intent, BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)

相关问题