- private BluetoothAdapter mBluetoothAdapter = null;
- private BluetoothSocket btSocket = null;
- private OutputStream outStream = null;
- private InputStream inStream = null;
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //这条是蓝牙串口通用的UUID,不要更改
- private static String address = "00:12:02:22:06:61"; // <==要连接的蓝牙设备MAC地址
- /*获得通信线路过程*/
- /*1:获取本地BlueToothAdapter*/
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if(mBluetoothAdapter == null)
- {
- Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
- finish();
- return;
- }
- if(!mBluetoothAdapter.isEnabled())
- {
- Toast.makeText(this, "Please enable your Bluetooth and re-run this program.", Toast.LENGTH_LONG).show();
- finish();
- return;
- }
- /*2:获取远程BlueToothDevice*/
- BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
- if(mBluetoothAdapter == null)
- {
- Toast.makeText(this, "Can't get remote device.", Toast.LENGTH_LONG).show();
- finish();
- return;
- }
- /*3:获得Socket*/
- try {
- btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
- } catch (IOException e) {
- Log.e(TAG, "ON RESUME: Socket creation failed.", e);
- }
- /*4:取消discovered节省资源*/
- mBluetoothAdapter.cancelDiscovery();
- /*5:连接*/
- try {
- btSocket.connect();
- Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
- } catch (IOException e) {
- try {
- btSocket.close();
- } catch (IOException e2) {
- Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
- }
- }
andorid蓝牙获取通信线路的基本过程
最新推荐文章于 2024-05-08 21:24:52 发布