鴻蒙OS 傳統(tǒng)藍牙本機管理

2020-09-18 15:04 更新

場景介紹

傳統(tǒng)藍牙本機管理主要是針對藍牙本機的基本操作,包括打開和關(guān)閉藍牙、設(shè)置和獲取本機藍牙名稱、掃描和取消掃描周邊藍牙設(shè)備、獲取本機藍牙 profile 對其他設(shè)備的連接狀態(tài)、獲取本機藍牙已配對的藍牙設(shè)備列表。

接口說明

接口名 功能描述
getDefaultHost(Context context) 獲取BluetoothHost實例,去管理本機藍牙操作。
enableBt() 打開本機藍牙。
disableBt() 關(guān)閉本機藍牙。
setLocalName(String name) 設(shè)置本機藍牙名稱。
getLocalName() 獲取本機藍牙名稱。
getBtState() 獲取本機藍牙狀態(tài)。
startBtDiscovery() 發(fā)起藍牙設(shè)備掃描。
cancelBtDiscovery() 取消藍牙設(shè)備掃描。
isBtDiscovering() 檢查藍牙是否在掃描設(shè)備中。
getProfileConnState(int profile) 獲取本機藍牙profile對其他設(shè)備的連接狀態(tài)。
getPairedDevices() 獲取本機藍牙已配對的藍牙設(shè)備列。

打開藍牙

  1. 調(diào)用 BluetoothHost 的 getDefaultHost(Context context) 接口,獲取 BluetoothHost 實例,管理本機藍牙操作。

  1. 調(diào)用 enableBt() 接口,打開藍牙。

  1. 調(diào)用 getBtState(),查詢藍牙是否打開。

   // 獲取藍牙本機管理對象
   BluetoothHost bluetoothHost = BluetoothHost.getDefaultHost(context);
   // 調(diào)用打開接口
   bluetoothHost.enableBt();
   // 調(diào)用獲取藍牙開關(guān)狀態(tài)接口
   int state = bluetoothHost.getBtState(); 

藍牙掃描

  1. 開始藍牙掃描前要先注冊廣播 BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED。

  1. 調(diào)用 startBtDiscovery() 接口開始進行掃描外圍設(shè)備。

  1. 如果想要獲取掃描到的設(shè)備,必須在注冊廣播時繼承實 現(xiàn)CommonEventSubscriber 類的 onReceiveEvent(CommonEventData data) 方法,并接收 EVENT_DEVICE_DISCOVERED 廣播。

   //開始掃描
   mBluetoothHost.startBtDiscovery();
   //接收系統(tǒng)廣播
   public class MyCommonEventSubscriber extends CommonEventSubscriber {
       @Override
       public void onReceiveEvent(CommonEventData var){
           Intent info = var.getIntent();
           if(info == null) return;
           //獲取系統(tǒng)廣播的action
           String action = info.getAction();
           //判斷是否為掃描到設(shè)備的廣播
           if(action == BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED){    
               IntentParams myParam = info.getParams();    
               BluetoothRemoteDevice device = (BluetoothRemoteDevice)myParam.getParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);
           }
       }
   }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號