1. 程式人生 > >藍芽API介紹及基本功能實現

藍芽API介紹及基本功能實現

本文已授權微信公眾號fanfan程式媛獨家釋出

ONE,傳統藍芽

  • BluetoothAdapter:本地藍芽裝置介面卡,用於管理藍芽的開啟/關閉、重新命名、掃描、配對、連線
  • BluetoothClass:藍芽裝置類,用於描述藍芽裝置型別
  • BluetoothDevice:遠端藍芽裝置類
  • BluetoothSocket:與tcpSocket類似,進行藍芽連線
  • BluetoothServerSocket:與tcpServerSocket類似,等待連線

獲取本地藍芽介面卡

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

開啟/關閉本地藍芽
adapter.enable();//開啟藍芽
adapter.disable();//關閉藍芽
adapter.isEnabled();//藍芽是否處於開啟狀態
adapter.getState();//獲取本機藍芽狀態 

通過監聽BluetoothAdapter.ACTION_STATE_CHANGED監聽藍芽狀態的改變

藍芽重新命名/獲取本機藍芽名
mAdapter.setName(name);//本地藍芽重新命名
mAdapter.getName();//獲取本機藍芽名

通過監聽BluetoothAdpater.ACTION_LOCAL_NAME_CHANGED監聽本機藍芽名稱的改變

藍芽可檢測性設定

有兩種方案,

首先第一種實現,簡單但對可檢測時間有限制

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		//預設可檢測時間為120秒,呼叫該方法最高可設定300秒
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
		startActivity(intent);


第二種實現方案,就是Android原始碼中的實現方案,可以任意規定可檢測時長,甚至永不超時均可(參考Android4.42原始碼)

/**
*mode有三種取值
*BluetoothAdapter.SCAN_MODE_CONNECTABLE:對已配對裝置可見,具有掃描功能
*BluetoothAdapter.SCAN_MODE_NONE:對所有裝置不可見,不具有掃描功能
*BluetoothAdapter.SCAN_MODE_CONNECTABLE_*DISCOVERABLE:對所有裝置可見,具有掃描功能
*duration為掃描時長
*/

mAdapter.setScanMode(mode, duration);
//設定alarm,當timeout結束時就關閉藍芽的可檢測性
BluetoothDiscoverableTimeoutReceiver.setDiscoverableAlarm(mContext, endTimestamp);
這是原始碼中的實現方案,但是BluetoothAdapter.setScanMode()沒有辦法去呼叫,只能利用反射

獲取已配對裝置列表

List<BluetoothDevice> list = (List<BluetoothDevice>) adapter.getBondedDevices();

開啟掃描/關閉掃描
adapter.startDiscovery();//開啟藍芽掃描功能
adapter.cancelDiscovery();//關閉藍芽掃描功能

在掃描到裝置時系統會發送BluetoothDevice.ACTION_FOUND的廣播,通過監聽該廣播可以獲取到裝置資訊

獲取到裝置後呼叫如下方式進行連線

BluetoothSocket _BluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

獲取到socket後可以獲取到輸入輸出流,這裡的uuid可以在網頁的uuid生成器線上生成,remotedevice和本機藍芽裝置的uuid必須相同

TWO,BLE低功耗藍芽

獲取藍芽介面卡的步驟同上,掃描ble裝置的方法如下:

//開啟藍芽掃描
mBluetoothAdapter.startLeScan(mLeScanCallback);
//結束藍芽掃描
mBluetoothAdapter.stopLeScan(mLeScanCallback);

其中mlLeScanCallback為BluetoothAdapter.LeScanCallback物件,
private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                       。。。
                   //掃描到裝置後回撥
}


掃描到裝置後可以進行連線,方法如下
mBluetoothGatt = mBluetoothDevice.connectGatt(BluetoothCODAService.this, false, mGattCallback);

其中mGattCallback為BluetoothGattCallback物件
 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

			if(newState == BluetoothProfile.STATE_CONNECTED){
	        //連線成功回撥
		
			}else if(newState == BluetoothProfile.STATE_DISCONNECTED){
               //連線失敗回撥
                      }
          public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                   
            if (status == BluetoothGatt.GATT_SUCCESS) { // 0
                                         //搜尋到服務回撥

      } else {
    //未搜尋到服務回撥
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                //接收到資料回撥
            }
        }

         @Override
         public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
          //傳送資料回撥
         }
    
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
          
        }

        @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                                 int status) {
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                                      int status) {
        }    

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
        
           }
    };

 }


           
連線成功後如果要進行通訊還必須搜尋服務
mBluetoothGatt.discoverServices();

搜尋服務後會回撥onServicesDiscovered方法。

至此,就可以進行讀寫資料了

//讀資料
mBluetoothGatt.readCharacteristic(characteristic);
//寫資料
 mBluetoothGatt.writeCharacteristic(characteristic,value);

關於低功耗藍芽的理論知識可以參考

鑑於多人私信我要藍芽demo,索性直接上傳資源,我整理了一篇低功耗相關的,連線裝置並讀取資料,附上demo的下載地址,供大家參考

http://download.csdn.net/detail/zrf1335348191/9525847

歡迎關注我的微信公眾號: