蓝牙配对和连接

最重要三个类:

BluetoothAdapter bluetoothAdapter

BluetoothSocket btSocket;

BluetoothDevice device



bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

bluetoothAdapter.startDiscovery();//开始搜索附近的蓝牙设备,搜索的时候会发出三个广播如下

startDiscovery()方法是一个异步方法,它会对其他蓝牙设备进行搜索,持续时间为12秒。搜索过程其实是在System Service中进行,我们可以通过cancelDiscovery()方法来停止这个搜索。在系统搜索蓝牙设备的过程中,系统可能会发送以下三个广播:ACTION_DISCOVERY_START(开始搜索),ACTION_DISCOVERY_FINISHED(搜索结束)和ACTION_FOUND(找到设备)。ACTION_FOUND这个才是我们想要的。所以在startDiscovery之前我们应该注册一个广播如下:

IntentFilter intentfilter = new IntentFilter(
				BluetoothDevice.ACTION_FOUND);
		bluetoothReceiver = new BluetoothReceiver();
		// 注册bluetoothReceiver
		registerReceiver(bluetoothReceiver, intentfilter);

广播接收类BluetoothReceiver的实现如下:
	public class BluetoothReceiver extends BroadcastReceiver {

		@SuppressLint("ShowToast")
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Toast.makeText(MainActivity.this, "扫描中...", 100).show();
			// device对象代表被扫描到的远程设备的对象
			// 将搜索到的蓝牙设备在ListView中显示出来

			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				String str = device.getName() + "|" + device.getAddress();

				if (lstDevices.indexOf(str) == -1)// 防止重复添加
					lstDevices.add(str); // 获取设备名称和mac地址
				adtDevices.notifyDataSetChanged();
				
			}

		}

	}

private List<String> lstDevices = new ArrayList<String>();

搜索到了之后就会把每一个蓝牙设备的name显示在一个listview中,点击listview中的某个设备之后,就会与之开始连接:

String str = lstDevices.get(arg2);
			String[] values = str.split("\\|");
			String address = values[1];
			Log.e("address", values[1]);

			uuid = UUID.fromString(SPP_UUID);
			Log.e("uuid", uuid.toString());
			// btDev是远端的蓝牙设备,get到之后,用btsocket得到其中的socket,建立连接的套接字
			BluetoothDevice btDev = bluetoothAdapter.getRemoteDevice(address);
			try {
				btSocket = (BluetoothSocket) btDev
						.getClass()
						.getMethod("createRfcommSocket",
								new Class[] { int.class })
						.invoke(btDev, Integer.valueOf(1));
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 取消查找
			bluetoothAdapter.cancelDiscovery();

			try {
				Toast.makeText(MainActivity.this, "正在连接...", Toast.LENGTH_SHORT)
						.show();
				btSocket.connect();
				Log.e(TAG,
						" BT connection established, data transfer link open.");

				Toast.makeText(MainActivity.this, "连接成功,进入控制界面",
						Toast.LENGTH_SHORT).show();

				// 打开控制界面
				Intent intent = new Intent(MainActivity.this,
						CtrlActivity.class);
				startActivity(intent);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e(TAG, " Connection failed.", e);
				Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT)
						.show();
			}


btSocket = btDev.createRfcommSocketToServiceRecord(SPP_UUID);

之前用这种方式给btSocket赋值时,btSocket.connect()就是抛出异常,后来改用如下方式就可以正常连接了

btSocket = (BluetoothSocket) btDev
                        .getClass()
                        .getMethod("createRfcommSocket",
                                new Class[] { int.class })
                        .invoke(btDev, Integer.valueOf(1));

注意在执行connect()操作之前一定要先

bluetoothAdapter.cancelDiscovery();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值