如何通过 Intent's putExtra 在 Android 上获取蓝牙设备对象?



我试图通过意图发送BluetoothDevice对象。当使用putExtra附加BluetoothDevice对象时没有问题,但是如果我试图通过getIntent获取BluetoothDevice,就会出现问题。

这里是问题和代码的细节

MainActivity

BluetoothDevice btDevice = deviceAdapter.getBleDevice(i);
Intent intent = new Intent(getApplicationContext(),bleDeviceControlActivity.class);
intent.putExtra("btDevice",btDevice);
startActivity(intent);

NextActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ble_device_control);
Intent intent = getIntent();
btDevice = intent.getSerializableExtra("btDevice");
}

问题发生在这段代码上btDevice = intent.getSerializableExtra("btDevice");

需要的类型是BluetoothDevice,但提供的类型是Serializable。我试着用

btDevice = (BluetoothDevice) intent.getSerializableExtra("btDevice");

但是这段代码仍然不能工作

BluetoothDevice实现Parcelable。你应该使用getParcelableExtra()而不是getSerializableExtra()

最新更新