1. 程式人生 > >藍芽模組之開發心得

藍芽模組之開發心得

這是本人部落格處女座,也許會有很多問題,還請各位大神指點。之所以寫這邊部落格,並不是因為自己這方面學的很深入,只是最近在初學藍芽模組,想對學習過程做個總結。

好的,廢話少說,直接開始正文。

使用 Android BluetoothAPI 來完成使用藍芽進行通訊的四項主要任務設定藍芽查詢區域性區域內的配對裝置或可用裝置連線裝置,以及在裝置之間傳輸資料要想實現這4個基礎的功能,還必須的知道藍芽的一些基本的類和介面:

1:BluetoothAdapter:

表示藍芽介面卡,也就是本地藍芽,一般的安卓手機或者平板都有藍芽模組,因此,你想通過藍芽去連線外部的藍芽裝置,必須要獲取本地藍芽介面卡,通過他才能外部藍芽進行連線。那麼如何獲取本地藍芽介面卡呢?方法很簡單

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}

我們需要注意的是,我們想要使用本地藍芽裝置,必須獲取系通許可權,獲取許可權的方式也很簡單:

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

獲取本地藍芽只能說明系統支援藍芽模組,還並不能與外部藍芽進行連線,我們還必須開啟藍芽裝置:

if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

2:BluetoothDevices:

我們希望與外部藍芽進行連線,就必須知道遠端外部藍芽的mac地址,所以,我們首先要獲取遠端外部藍芽。由於我們使用的android手機或者安卓系統平板,他們在此之前已經連線過很多藍芽裝置,因此存在本地已經配對的藍芽列表,那麼我們如何獲得已經配對的藍芽裝置呢?

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
    // Loop through paired devices
    for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}

假如我們需要連線的是一個新的(未配對過的)藍芽裝置,因此我們必須開啟藍芽發現,藍芽發現是一個重量級的過程,耗時且耗系統資源,因此當我們發現遠端藍芽之後,必須停止藍芽發現。那麼,我們如何知道系統已經掃描到外部藍芽了呢?我們通過廣播去接受系統的藍芽發現。

開啟藍芽發現:

bluetoothAdapter.startDiscovery();

註冊廣播進行接收:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy


3:藍芽連線

我們假定存在外部藍芽裝置,即存在藍芽的服務端,在此只考慮藍芽客戶端的情況。

                        


在執行藍芽連線之前,一定要取消藍芽發現,取消藍芽發現也挺簡單的。只需要呼叫BluetoothAdapter.cancelDiscovery();由於藍芽連線是一個阻塞的方法,因此,我們新建一個執行緒實現藍芽連線是一個不錯的方式,如果在UI執行緒中直接呼叫藍芽連線的方法,很有可能造成ANR錯誤,於是直接上程式碼:

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() {
		      btAdapter.cancelDiscovery();

		      try {
		          mmSocket.connect();
		      } catch (IOException connectException) {
		          try {
		              mmSocket.close();
		          } catch (IOException closeException) { }
		          return;
		      }
		  }
		  public void cancel() {
		      try {
		          mmSocket.close();
		      } catch (IOException e) { }
		  }
		}

4:藍芽通訊

藍芽連線完成以後,只需要獲取mmSocket埠的藍芽輸入,輸出流即可與外部藍芽進行通訊。

本人剛剛接觸藍芽這方面,所瞭解的也只是冰山一角,不求給讀者帶來多大的幫助,只求與讀者一起學習。