http://blog.youkuaiyun.com/danericola/article/details/7532425
今天准备在自己的游戏中加入蓝牙功能,于是将Android SDK Sample中的BluetoothChat看了看,发现基本上大部分的代码都可以复用,于是乎乾坤大挪移了一番,总算没有错误了,可是在我的Nexus上一运行,悲剧了,蓝牙明明打开了,可是却不能进入到DeviceListActivity,看了看代码,我是在onActivityResult中判断蓝牙打开成功后,才会启动DeviceListActivity,难道这么简单的代码都会出错吗?没办法只好调试一下了,一调试才发现,原来调用startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH)后,请求开启蓝牙的对话框刚弹出来,onActivityResult函数就已经被调用了,而且其resultCode还是Activity.RESULT_CANCELED,而当在对话框上选择开启蓝牙后,onActivityResult函数反而不会被调用了,我了个擦,这是怎么回事。
代码如下:
- private void enableBluetooth() {
- if (D) Log.d(TAG, "enable bluetooth");
- Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
- }
- private void selectDevice() {
- Intent serverIntent = new Intent(Linkage.this, BtDeviceList.class);
- startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
- }
- private void enterVsMode() {
- if (mBtAdapter == null) return;
- if (mBtAdapter.isEnabled()) {
- selectDevice();
- } else {
- enableBluetooth();
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- switch (requestCode) {
- case REQUEST_ENABLE_BLUETOOTH:
- // When the request to enable Bluetooth returns
- if (resultCode == Activity.RESULT_OK) {
- selectDevice();
- } else {
- // User did not enable Bluetooth or an error occured
- Toast.makeText(this, R.string.bt_open_failed, Toast.LENGTH_SHORT).show();
- }
- case REQUEST_CONNECT_DEVICE:
- // When DeviceListActivity returns with a device to connect
- if (resultCode == Activity.RESULT_OK) {
- // Get the device MAC address
- String address = data.getExtras().getString(BtDeviceList.EXTRA_DEVICE_ADDRESS);
- // Get the BLuetoothDevice object
- BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
- // Attempt to connect to the device
- mBtService.connect(device);
- }
- break;
- }
- }