Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 學習指南之四十一:藍牙開發完全解析

編輯:關於 Android 開發

藍牙傳輸資料是行動裝置常用的通訊方式,在 Android 中,藍牙模組至今仍相當實用。本文就詳細講解 Android 藍牙模組的使用方法。

1、藍牙相關權限

  1. <uses-permission android:name="android.permission.BLUETOOTH" />
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2、配置本機藍牙模組

這裡首先要認識操作藍牙的一個核心類別——BluetoothAdapter。

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// 直接開啟系統的藍牙設定面板
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0x1);
// 直接開啟藍牙
adapter.enable();
// 關閉藍牙
adapter.disable();
// 開啟本機的藍牙發現功能(預設開啟 120 秒,最長可延長至 300 秒)
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);

3、搜尋藍牙裝置

使用 BluetoothAdapter 的 startDiscovery() 方法來搜尋藍牙裝置。

startDiscovery() 是一個非同步方法,呼叫後會立即返回。它會對其他藍牙裝置進行搜尋,整個過程大約持續 12 秒。由於搜尋實際上是在一個 System Service 中進行的,因此可以呼叫 cancelDiscovery() 方法來停止搜尋(此方法在尚未執行 discovery 請求時也能呼叫)。

發出 Discovery 請求後,系統開始搜尋藍牙裝置,過程中會送出以下三個廣播:

ACTION_DISCOVERY_START:開始搜尋
ACTION_DISCOVERY_FINISHED:搜尋結束
ACTION_FOUND:找到裝置,這個 Intent 含有兩個 extra 欄位:EXTRA_DEVICE 與 EXTRA_CLASS,分別包含 BluetoothDevice 與 BluetoothClass。

我們可以自己註冊對應的 BroadcastReceiver 來接收這些廣播,藉此實現某些功能。

// 建立一個接收 ACTION_FOUND 廣播的 BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
     public void onReceive(Context context, Intent intent) {
         String action = intent.getAction();
         if (BluetoothDevice.ACTION_FOUND.equals(action)) {
             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
             mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
         }
     }
};
// 註冊 BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // 別忘了之後要解除綁定

4、藍牙 Socket 通訊

若想在兩個藍牙裝置之間建立連線,就必須實作伺服器端與用戶端的機制。當兩個裝置在同一個 RFCOMM channel 下各自擁有一個連線的 BluetoothSocket,才算真正建立了連線。

伺服器端與用戶端取得 BluetoothSocket 的途徑不同:伺服器端是透過 accept 一個連入的連線來取得,而用戶端則是透過開啟一個連到伺服器的 RFCOMM channel 來取得。

伺服器端的實作

呼叫 BluetoothAdapter 的 listenUsingRfcommWithServiceRecord(String, UUID) 方法來取得 BluetoothServerSocket(UUID 供用戶端與伺服器端配對之用)。
呼叫 BluetoothServerSocket 的 accept() 方法監聽連線請求,若收到請求便回傳一個 BluetoothSocket 實例(此方法為 blocking,應放在新執行緒中執行)。
若不想再接受其他連線,就呼叫 BluetoothServerSocket 的 close() 方法釋放資源(呼叫該方法後,先前取得的 BluetoothSocket 實例並不會被關閉。但由於 RFCOMM 在同一時刻只允許一條 channel 上有一個連線,因此一般在 accept 一個連線後,便會 close 掉 BluetoothServerSocket)。

private class AcceptThread extends Thread {
     private final BluetoothServerSocket mmServerSocket;
     public AcceptThread() {
         BluetoothServerSocket tmp = null;
         try {
             // MY_UUID 是應用的 UUID 字串,用戶端程式碼也會用到
             tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
         } catch (IOException e) { }
         mmServerSocket = tmp;
     }
     public void run() {
         BluetoothSocket socket = null;
         while (true) {
             try {
                 socket = mmServerSocket.accept();
             } catch (IOException e) { break; }
             if (socket != null) {
                 manageConnectedSocket(socket);
                 try { mmServerSocket.close(); } catch (IOException e) { }
                 break;
             }
         }
     }
     public void cancel() {
         try { mmServerSocket.close(); } catch (IOException e) { }
     }
}

用戶端的實作

透過搜尋取得伺服器端的 BluetoothDevice。
呼叫 BluetoothDevice 的 createRfcommSocketToServiceRecord(String, UUID) 方法取得 BluetoothSocket(該 UUID 應與伺服器端相同)。
呼叫 BluetoothSocket 的 connect() 方法(此方法為 blocking),若 UUID 與伺服器端相符、且連線被伺服器端 accept,connect() 便會返回。
注意:在呼叫 connect() 之前,應先確認目前沒有正在搜尋裝置,否則連線會變得非常慢且容易失敗。

private class ConnectThread extends Thread {
     private final BluetoothSocket mmSocket;
     private final BluetoothDevice mmDevice;
     public ConnectThread(BluetoothDevice device) {
         BluetoothSocket tmp = null;
         mmDevice = device;
         try {
             tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
         } catch (IOException e) { }
         mmSocket = tmp;
     }
     public void run() {
         mBluetoothAdapter.cancelDiscovery();
         try {
             mmSocket.connect();
         } catch (IOException connectException) {
             try { mmSocket.close(); } catch (IOException closeException) { }
             return;
         }
         manageConnectedSocket(mmSocket);
     }
     public void cancel() {
         try { mmSocket.close(); } catch (IOException e) { }
     }
}

連線管理(資料通訊)

分別透過 BluetoothSocket 的 getInputStream() 與 getOutputStream() 方法取得 InputStream 與 OutputStream。
使用 read(bytes[]) 與 write(bytes[]) 方法進行讀寫。
注意:read(bytes[]) 會一直 blocking,直到從串流中讀到資料;而 write(bytes[]) 並不總是 blocking(例如當另一裝置沒有及時 read,或中間緩衝區已滿時,write 才會 block)。

private class ConnectedThread extends Thread {
     private final BluetoothSocket mmSocket;
     private final InputStream mmInStream;
     private final OutputStream mmOutStream;
     public ConnectedThread(BluetoothSocket socket) {
         mmSocket = socket;
         InputStream tmpIn = null;
         OutputStream tmpOut = null;
         try {
             tmpIn = socket.getInputStream();
             tmpOut = socket.getOutputStream();
         } catch (IOException e) { }
         mmInStream = tmpIn;
         mmOutStream = tmpOut;
     }
     public void run() {
         byte[] buffer = new byte[1024];
         int bytes;
         while (true) {
             try {
                 bytes = mmInStream.read(buffer);
                 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
             } catch (IOException e) { break; }
         }
     }
     public void write(byte[] bytes) {
         try { mmOutStream.write(bytes); } catch (IOException e) { }
     }
     public void cancel() {
         try { mmSocket.close(); } catch (IOException e) { }
     }
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved