在Android中从Parcelable数组中获取值

3
我需要解析并获取以下内容的值:
Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");

我的目标是从上面的Parcelable[]中获取UUID。如何实现?
我的目标是从上述 Parcelable[] 中获取 UUID。如何实现?
4个回答

6

尝试像这样做。这对我有用:

   if(BluetoothDevice.ACTION_UUID.equals(action)) {
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
     Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
     for (int i=0; i<uuidExtra.length; i++) {
       out.append("\n  Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString());
     }

希望这能帮到您!

4
您需要遍历Parcelable[],将每个Parcelable转换为ParcelUuid,并使用ParcelUuid.getUuid()获取UUID。虽然您可以像另一个答案中那样在Parcelable上使用toString(),但这只会给您一个表示UUID的字符串,而不是UUID对象。
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if (uuids != null) {
    for (Parcelable parcelable : uuids) {
        ParcelUuid parcelUuid = (ParcelUuid) parcelable;
        UUID uuid = parcelUuid.getUuid();
        Log.d("ParcelUuidTest", "uuid: " + uuid);
    }       
}       

1

接受的答案引用了文档并正确地指出返回的对象是ParcelUuid类型。然而,他没有提供链接; 这里是链接: BluetoothDevice.EXTRA_UUID

此外,提供的代码有两个错误;一是它没有引用与问题相同的方法,二是它不能编译(在这里进行一些语言学的自由)。为了纠正这两个问题,代码应该是:

Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");
if (uuidExtra != null) {
   for (int j=0; j<uuidExtra.length; j++) {
      ParcelUuid extraUuidParcel = (ParcelUuid)uuidExtra[j];
      // put code here
   }
}

第三,如果需要额外的保护(虽然通常情况下对象应该总是ParcelUuid),则以下内容可以在for中使用:

   ParcelUuid extraUuidParcel = uuidExtra[j] instanceof ParcelUuid ? ((ParcelUuid) uuidExtra[j]) : null;
   if (extraUuidParcel != null) {
      // put code here
   }

这个解决方案是由Arne提供的。我还不能添加评论,此外我提供了文档页面 :)

-2

从文档中可以看到,extra 是一个 ParcelUuid

因此,您应该使用

ParcelUuid uuidExtra intent.getParcelableExtra("android.bluetooth.device.extra.UUID");
UUID uuid = uuidExtra.getUuid();

希望这有所帮助。

第二行抛出错误 @Ian Warwick - Venky
1
@Venky,既然你将其标记为答案,现在它是否正常工作了?你是如何让它正常工作的? - Ian Warwick
4
这个解决方案没有起作用。你怎么能接受一个不起作用的例子呢? - Deepika Lalra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接