天天看點

Android藍牙開發和BLE通訊Demo

源碼位址

普通藍牙:

  • 1. 配置藍牙權限
<!--允許程式連接配接配對過的藍牙裝置-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <!--允許程式進行發現和配對新的藍牙裝置-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
           
  • 2. 打開藍牙
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {    //是否支援藍牙
    return;
}
if (!mBluetoothAdapter.isEnabled()) {
    // 打開藍牙方式一,直接打開
    mBluetoothAdapter.enable();
    // 打開藍牙方式二,調用對話框打開: onActivityResult()提供打開成功的回調
//            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(intent, 0);
    }
           
  • 3. 查找裝置
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver來取得搜尋結果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);    // 擷取藍牙裝置的連接配接狀态
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, intent);
           
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevices.add(bluetoothDevice);

        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            // 擷取藍牙裝置的連接配接狀态
            if (mBluetoothDevice == null) {
                return;
            }
            int connectState = mBluetoothDevice.getBondState();
            // 已配對
            if (connectState == BluetoothDevice.BOND_BONDED) {
                try {
                    show("用戶端:開始連接配接:");
                    ClientThread clientConnectThread = new ClientThread(mBluetoothDevice);
                    clientConnectThread.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {  //搜尋結束
            mDeviceAdapter.notifyDataSetChanged();
        }

    }
};
           
  • 4. 配對連接配接
BluetoothDevice bluetoothDevice = mDevices.get(position);
// 藍牙配對
if (BluetoothDevice.BOND_NONE == bluetoothDevice.getBondState()) {
    mBluetoothDevice = bluetoothDevice;
    createBond(mDevices.get(position));
} else {// 藍牙配對過,直接連接配接
    try {
        show("用戶端:開始連接配接:");
        ClientThread clientConnectThread = new ClientThread(bluetoothDevice);
        clientConnectThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
           
/**
 * 配對裝置
 */
private void createBond(BluetoothDevice bluetoothDevice) {
    try {
        Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
        createBondMethod.invoke(bluetoothDevice);
    } catch (Exception e) {
        e.getStackTrace();
    }
}
/**
 * 與裝置解除配對
 */
public boolean removeBond(BluetoothDevice bluetoothDevice) throws Exception {
    Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
    Boolean returnValue = (Boolean) removeBondMethod.invoke(bluetoothDevice);
    return returnValue.booleanValue();
}

/**
 * 擷取配對過的裝置
 */
private Set<BluetoothDevice> getBondedDevices() {
    pairedDevices = mBluetoothAdapter.getBondedDevices();
    for (BluetoothDevice device : pairedDevices) {
        Log.d(TAG, device.getName() + " " + device.getAddress());
    }
    return pairedDevices;
}
           
  • 5. 建立連接配接,socket通訊
/**
 * 開啟用戶端
 */
private class ClientThread extends Thread {
    private BluetoothDevice bluetoothDevice;

    public ClientThread(BluetoothDevice bluetoothDevice) {
        this.bluetoothDevice = bluetoothDevice;
    }

    public void run() {
        try {
            //建立一個Socket連接配接:隻需要伺服器在注冊時的UUID号
            mBluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(
                    UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));   //UUID被用于唯一辨別一個服務,如檔案傳輸服務,序列槽服務、列印機服務等
            //連接配接
            show("用戶端:開始連接配接...");
            mBluetoothSocket.connect();
            show("用戶端:連接配接成功");
            //啟動接受資料
            show("用戶端:啟動接受資料");
            ReadThread mreadThread = new ReadThread(mBluetoothSocket);
            mreadThread.start();
        } catch (IOException e) {
            show("用戶端:連接配接服務端異常!斷開連接配接重新試一試");
            e.printStackTrace();
        }
    }
}
           
/**
 * 讀取資料
 */
private class ReadThread extends Thread {
    private BluetoothSocket bluetoothSocket;

    public ReadThread(BluetoothSocket bluetoothSocket) {
        this.bluetoothSocket = bluetoothSocket;
    }

    public void run() {
        byte[] buffer = new byte[];
        int bytes;
        InputStream is = null;
        try {
            is = bluetoothSocket.getInputStream();
            ToastUtils.show("用戶端:獲得輸入流");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        while (true) {
            try {
                if ((bytes = is.read(buffer)) > ) {
                    byte[] buf_data = new byte[bytes];
                    for (int i = ; i < bytes; i++) {
                        buf_data[i] = buffer[i];
                    }
                    String s = new String(buf_data);
                    ToastUtils.show("用戶端:讀取資料了" + s);
                }
            } catch (IOException e) {
                try {
                    is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                break;
            }
        }
    }
}
           

BLE開發:

  • 1. 配置藍牙權限
<!--允許程式連接配接配對過的藍牙裝置-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <!--允許程式進行發現和配對新的藍牙裝置-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <!--required為true:應用隻能在支援BLE的裝置上安裝運作;required為false:Android裝置均可正常安裝運作-->
    <uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true" />
           
  • 擷取BLE裝置