自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

HarmonyOS Sample之Bluetooth傳統(tǒng)藍牙的使用

開發(fā) 前端 OpenHarmony
主要是針對藍牙本機的基本操作,包括:打開和關閉藍牙、設置和獲取本機藍牙名稱、掃描和取消掃描周邊藍牙設備、獲取本機藍牙profile對其他設備的連接狀態(tài)、獲取本機藍牙已配對的藍牙設備列表。

[[424760]]

想了解更多內(nèi)容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術社區(qū)

https://harmonyos.51cto.com

1.介紹

本示例演示了如何對藍牙進行基本操作,

傳統(tǒng)藍牙本機管理:

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

傳統(tǒng)藍牙遠端管理操作:

主要是針對遠端藍牙設備的基本操作,包括:獲取遠端藍牙設備地址、類型、名稱和配對狀態(tài),以及向遠端設備發(fā)起配對。

傳統(tǒng)藍牙和BLE的的概念請參考 藍牙開發(fā)概述

還有一個小知識點,

調(diào)用藍牙的打開接口需要ohos.permission.USE_BLUETOOTH權(quán)限,

調(diào)用藍牙掃描接口需要ohos.permission.LOCATION權(quán)限和ohos.permission.DISCOVER_BLUETOOTH權(quán)限。

2.搭建環(huán)境

安裝DevEco Studio,詳情請參考DevEco Studio下載

設置DevEco Studio開發(fā)環(huán)境,DevEco Studio開發(fā)環(huán)境需要依賴于網(wǎng)絡環(huán)境,需要連接上網(wǎng)絡才能確保工具的正常使用,可以根據(jù)如下兩種情況來配置開發(fā)環(huán)境:

如果可以直接訪問Internet,只需進行下載HarmonyOS SDK操作。

如果網(wǎng)絡不能直接訪問Internet,需要通過代理服務器才可以訪問,請參考配置開發(fā)環(huán)境。

下載源碼后,使用DevEco Studio 打開項目,模擬器運行即可。

真機運行需要將config.json中的buddleName修改為自己的,如果沒有請到AGC上進行配置,參見 使用模擬器進行調(diào)試 。

3.代碼結(jié)構(gòu)

HarmonyOS Sample 之 Bluetooth 傳統(tǒng)藍牙的使用-鴻蒙HarmonyOS技術社區(qū)

4.實例講解

4.1.界面布局

 布局效果

HarmonyOS Sample 之 Bluetooth 傳統(tǒng)藍牙的使用-鴻蒙HarmonyOS技術社區(qū)HarmonyOS Sample 之 Bluetooth 傳統(tǒng)藍牙的使用-鴻蒙HarmonyOS技術社區(qū)

4.2.后臺代碼

4.2.1 涉及的相關類

SDK提供的核心類:

BluetoothHost.java//藍牙主機,可以管理藍牙,提供了藍牙的基本操作,打開/關閉/獲取狀態(tài)等。

BluetoothRemoteDevice.java//藍牙對象,用于建立與對端設備的連接并查詢名稱、設備類型和配對狀態(tài)等信息。

自定義的類:

BluetoothItemProvider.java//藍牙設備列表項提供程序

BluetoothEventListener.java//藍牙事件監(jiān)聽接口

BluetoothPlugin.java//藍牙插件

BluetoothDevice.java//藍牙對象簡易模型

4.2.2 BluetoothPlugin.java 藍牙插件提供的功能

a.初始化BluetoothHost藍牙主機對象getDefaultHost

  1. /** 
  2. * 初始化藍牙主機對象和監(jiān)聽器 
  3. * Initializes the Bluetooth Host on device. 
  4. * @param eventListener interface to update the Bluwettoth events 
  5. */ 
  6. public void initializeBluetooth(BluetoothEventListener eventListener) { 
  7.   bluetoothEventListener = eventListener; 
  8.   btHost = BluetoothHost.getDefaultHost(mainSliceContext); 
  9.   LogUtil.info(TAG, "initializeBluetooth, btHost:"+btHost); 

b.開啟/關閉藍牙/獲取藍牙狀態(tài)enableBt/disableBt/getBtState

  1. /** 
  2. * 開啟藍牙 
  3. * 低功耗藍牙(BLE ,Bluetooth Low Energy),LE是2010年才提出的 
  4. * 經(jīng)典藍牙(classic Bluetooth),包括BR,EDR和HS(AMP)三種模式 
  5. * Enables the Bluetooth on device. 
  6. */ 
  7. public void enableBluetooth() { 
  8.   LogUtil.info("enableBluetooth""getBtState:"+btHost.getBtState()); 
  9.   //獲取藍牙主機的狀態(tài) 
  10.   if (btHost.getBtState() == STATE_OFF || 
  11.           btHost.getBtState() == STATE_TURNING_OFF || 
  12.           btHost.getBtState() ==STATE_BLE_ON) { 
  13.       LogUtil.info("enableBluetooth""enableBt:"+btHost.getBtState()); 
  14.       //開啟藍牙 
  15.       btHost.enableBt(); 
  16.   } 
  17.   //事件通知藍牙狀態(tài)發(fā)生改變 
  18.   bluetoothEventListener.notifyBluetoothStatusChanged(btHost.getBtState()); 
  19. /** 
  20. * 關閉藍牙 
  21. * Disables the Bluetooth on device. 
  22. */ 
  23. public void disableBluetooth() { 
  24.   if (btHost.getBtState() == STATE_ON || btHost.getBtState() == STATE_TURNING_ON) { 
  25.       btHost.disableBt(); 
  26.   } 
  27.   bluetoothEventListener.notifyBluetoothStatusChanged(btHost.getBtState()); 
  28.  
  29. /** 
  30. * 獲取藍牙狀態(tài) 
  31. * Obtains the status of the Bluetooth on device. 
  32. * @return status of Bluetooth on device 
  33. */ 
  34. public int getBluetoothStatus() { 
  35.   LogUtil.info("getBluetoothStatus""getBluetoothStatus:"+btHost.getBtState()); 
  36.   //獲取藍牙狀態(tài) 
  37.   return btHost.getBtState(); 

c.開始藍牙發(fā)現(xiàn)startBtDiscovery

還要注意的是藍牙發(fā)現(xiàn)操作需要申請位置權(quán)限。

  1. /** 
  2. * 開始藍牙發(fā)現(xiàn) 
  3. * Scans the currently available bluetooth devices 
  4. */ 
  5. public void startBtDiscovery() { 
  6.   if (!btHost.isBtDiscovering()) { 
  7.       //開始發(fā)現(xiàn)設備,大約需要12.8s 
  8.       btHost.startBtDiscovery(); 
  9.   } 
  10.  
  11. /** 
  12. *判斷是否有權(quán)限 
  13. */ 
  14. private boolean hasPermission() { 
  15.   return mainSliceContext.verifySelfPermission(Constants.PERM_LOCATION) == IBundleManager.PERMISSION_GRANTED; 
  16.  
  17. /** 
  18. * 啟動藍牙掃描 
  19. * Scans the currently available bluetooth devices 
  20. */ 
  21. public void startBtScan() { 
  22.   LogUtil.info("startBtScan""getBtState:"+btHost.getBtState()); 
  23.   int btStatus = btHost.getBtState(); 
  24.  
  25.   if (btStatus == STATE_ON) { 
  26.       if (hasPermission()) { 
  27.           startBtDiscovery(); 
  28.       } else { 
  29.           requestPermission(); 
  30.       } 
  31.   } 

d.藍牙設備配對及獲取已配對的設備列表startPair/getPairedDevices

  1. /** 
  2. * 啟動與給定地址的藍牙設備配對。 
  3. * initiate pairing with bluetooth device of given address. 
  4. * @param pairAddress address of the bluetooth device 
  5. */ 
  6. public void startPair(String pairAddress) { 
  7.   Optional<BluetoothRemoteDevice> optBluetoothDevice = getSelectedDevice(pairAddress); 
  8.   optBluetoothDevice.ifPresent(BluetoothRemoteDevice::startPair); 
  9.  
  10. /** 
  11. * 獲取要配對的設備 
  12. * @param pairAddress 
  13. * @return 
  14. */ 
  15. private Optional<BluetoothRemoteDevice> getSelectedDevice(String pairAddress) { 
  16.   if (pairAddress != null && !pairAddress.isEmpty()) { 
  17.       for (BluetoothRemoteDevice device : availableDevices) { 
  18.           if (device.getDeviceAddr().equals(pairAddress)) { 
  19.               return Optional.ofNullable(device); 
  20.           } 
  21.       } 
  22.   } 
  23.   return Optional.empty(); 
  24.  
  25. /** 
  26. * 獲取已配對的藍牙設備列表 
  27. * Obtains the paired Bluetooth device list. 
  28. * @return paired Bluetooth devices 
  29. */ 
  30. public List<BluetoothDevice> getPairedDevices() { 
  31.   //btHost.getPairedDevices() 
  32.   Set<BluetoothRemoteDevice> pairedDevices = new HashSet<>(btHost.getPairedDevices()); 
  33.   return getBluetoothDevices(pairedDevices); 

e.藍牙事件的訂閱/取消 及 相關事件的處理

在處理藍牙事件的同時,通過BluetoothEventListener通知MainAbilitySlice。

  1. /** 
  2. * 訂閱藍牙事件 
  3. * Subscribe for Events of Bluetooth using CommonEvents 
  4. */ 
  5. public void subscribeBluetoothEvents() { 
  6.   MatchingSkills matchingSkills = new MatchingSkills(); 
  7.   //表示藍牙狀態(tài)改變時上報的事件。 
  8.   matchingSkills.addEvent(BluetoothHost.EVENT_HOST_STATE_UPDATE); 
  9.   //指示藍牙掃描開始時報告的事件。 
  10.   matchingSkills.addEvent(BluetoothHost.EVENT_HOST_DISCOVERY_STARTED); 
  11.   //指示藍牙掃描完成時報告的事件。 
  12.   matchingSkills.addEvent(BluetoothHost.EVENT_HOST_DISCOVERY_FINISHED); 
  13.   //表示發(fā)現(xiàn)遠程藍牙設備時上報的事件。 
  14.   matchingSkills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED); 
  15.   //遠程藍牙設備配對時上報的事件。 
  16.   matchingSkills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_PAIR_STATE); 
  17.  
  18.   //用于創(chuàng)建 CommonEventSubscriber 實例并傳遞 subscribeInfo 參數(shù)的構(gòu)造函數(shù)。 
  19.   CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); 
  20.  
  21.   //訂閱者 
  22.   commonEventSubscriber = new CommonEventSubscriber(subscribeInfo) { 
  23.       @Override 
  24.       public void onReceiveEvent(CommonEventData commonEventData) { 
  25.           Intent intent = commonEventData.getIntent(); 
  26.           handleIntent(intent); 
  27.       } 
  28.   }; 
  29.   try { 
  30.       //完成訂閱 
  31.       CommonEventManager.subscribeCommonEvent(commonEventSubscriber); 
  32.   } catch (RemoteException e) { 
  33.       LogUtil.error(TAG, "RemoteException while subscribe bluetooth events."); 
  34.   } 
  35.  
  36. /** 
  37. * 取消訂閱藍牙事件 
  38. * UnSubscribe for Bluetooth Events 
  39. */ 
  40. public void unSubscribeBluetoothEvents() { 
  41.   if (commonEventSubscriber != null) { 
  42.       try { 
  43.           CommonEventManager.unsubscribeCommonEvent(commonEventSubscriber); 
  44.       } catch (RemoteException e) { 
  45.           LogUtil.error(TAG, "RemoteException while unsubscribing bluetooth events."); 
  46.       } 
  47.       commonEventSubscriber = null
  48.   } 
  49.  
  50.  
  51.  
  52. private void handleIntent(Intent intent) { 
  53.   if (intent == null) { 
  54.       return
  55.   } 
  56.  
  57.   String action = intent.getAction(); 
  58.   switch (action) { 
  59.       //狀態(tài)更新 
  60.       case BluetoothHost.EVENT_HOST_STATE_UPDATE: 
  61.           handleHostStateUpdate(); 
  62.           break; 
  63.       //掃描開始 
  64.       case BluetoothHost.EVENT_HOST_DISCOVERY_STARTED: 
  65.           handleDeviceDiscoveryState(true); 
  66.           break; 
  67.       //表示發(fā)現(xiàn)遠程藍牙設備時上報的事件。 
  68.       case BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED: 
  69.           handleBluetoothDeviceDiscovered(intent); 
  70.           break; 
  71.       // 掃描完成 
  72.       case BluetoothHost.EVENT_HOST_DISCOVERY_FINISHED: 
  73.           handleDeviceDiscoveryState(false); 
  74.           break; 
  75.       //表示遠程藍牙設備配對時上報的事件。 
  76.       case BluetoothRemoteDevice.EVENT_DEVICE_PAIR_STATE: 
  77.           handleDevicePairState(intent); 
  78.           break; 
  79.       default
  80.           LogUtil.info(TAG, "Action not handled : " + action); 
  81.   } 
  82.  
  83. private void handleDevicePairState(Intent intent) { 
  84.   BluetoothRemoteDevice btRemoteDevice = intent.getSequenceableParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE); 
  85.   if (btRemoteDevice.getPairState() == BluetoothRemoteDevice.PAIR_STATE_PAIRED) { 
  86.       //更新2個設備列表 
  87.       updateAvailableDeviceList(btRemoteDevice); 
  88.       updatePairedDeviceList(); 
  89.   } 
  90.  
  91. private void handleDeviceDiscoveryState(boolean isStarted) { 
  92.   //處理掃描狀態(tài)變化事件通知 
  93.   bluetoothEventListener.notifyDiscoveryState(isStarted); 
  94.  
  95. /** 
  96. * 處理藍牙狀態(tài)變化通知 
  97. */ 
  98. private void handleHostStateUpdate() { 
  99.  
  100.   int status = getBluetoothStatus(); 
  101.   bluetoothEventListener.notifyBluetoothStatusChanged(status); 
  102.  
  103. /** 
  104. * 處理藍牙發(fā)現(xiàn)事件 
  105. * @param intent 
  106. */ 
  107. private void handleBluetoothDeviceDiscovered(Intent intent) { 
  108.   BluetoothRemoteDevice btRemoteDevice = 
  109.           intent.getSequenceableParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE); 
  110.  
  111.   //未配對的設備 
  112.   if (btRemoteDevice.getPairState() != BluetoothRemoteDevice.PAIR_STATE_PAIRED) { 
  113.       //發(fā)現(xiàn)后添加到可用的藍牙設備 
  114.       availableDevices.add(btRemoteDevice); 
  115.   } 
  116.   bluetoothEventListener.updateAvailableDevices(getAvailableDevices()); 
  117.  
  118.  
  119. /** 
  120. * 更新可用設備列表 
  121. * @param remoteDevice 
  122. */ 
  123. private void updateAvailableDeviceList(BluetoothRemoteDevice remoteDevice) { 
  124.   //移除以配對的藍牙 
  125.   availableDevices.removeIf(device -> device.getDeviceAddr().equals(remoteDevice.getDeviceAddr())); 
  126.   bluetoothEventListener.updateAvailableDevices(getAvailableDevices()); 
  127.  
  128. private void updatePairedDeviceList() { 
  129.   //刷新已配對的藍牙列表 
  130.   bluetoothEventListener.updatePairedDevices(getPairedDevices()); 
  131.  
  132. public List<BluetoothDevice> getAvailableDevices() { 
  133.   return getBluetoothDevices(availableDevices); 
  134.  
  135. /** 
  136. * 獲取已配對的藍牙設備列表 
  137. * Obtains the paired Bluetooth device list. 
  138. * @return paired Bluetooth devices 
  139. */ 
  140. public List<BluetoothDevice> getPairedDevices() { 
  141.   //btHost.getPairedDevices() 
  142.   Set<BluetoothRemoteDevice> pairedDevices = new HashSet<>(btHost.getPairedDevices()); 
  143.   return getBluetoothDevices(pairedDevices); 
  144.  
  145. private List<BluetoothDevice> getBluetoothDevices(Set<BluetoothRemoteDevice> remoteDeviceList) { 
  146.   List<BluetoothDevice> btDevicesList = new ArrayList<>(); 
  147.   if (remoteDeviceList != null) { 
  148.       // 
  149.       btDevicesList = remoteDeviceList.stream().map(BluetoothDevice::new).collect(Collectors.toList()); 
  150.   } 
  151.   return btDevicesList; 

4.2.3 BluetoothEventListener.java 自定義的藍牙事件監(jiān)聽器接口

  1. public interface BluetoothEventListener { 
  2.  void updateAvailableDevices(List<BluetoothDevice> bluetoothDevice); 
  3.  
  4.  void updatePairedDevices(List<BluetoothDevice> bluetoothDevice); 
  5.  
  6.  void notifyBluetoothStatusChanged(int bluetoothStatus); 
  7.  
  8.  void notifyDiscoveryState(boolean isStarted); 
  9.  } 

4.2.4 BluetoothItemProvider.java 藍牙設備列表提供程序

這個可以作為一個標準件了,每個ListContainer都可以用它,包括了列表的通用操作,像數(shù)據(jù)更新,點擊事件等。

  1. public class BluetoothItemProvider extends BaseItemProvider { 
  2.  private final AbilityContext context; 
  3.  
  4.  private List<BluetoothDevice> bluetoothDeviceList; 
  5.  
  6.  public BluetoothItemProvider(AbilityContext context, List<BluetoothDevice> itemList) { 
  7.      this.context = context; 
  8.      bluetoothDeviceList = itemList; 
  9.  } 
  10.  
  11.  @Override 
  12.  public int getCount() { 
  13.      return bluetoothDeviceList.size(); 
  14.  } 
  15.  
  16.  @Override 
  17.  public Object getItem(int position) { 
  18.      return bluetoothDeviceList.get(position); 
  19.  } 
  20.  
  21.  @Override 
  22.  public long getItemId(int position) { 
  23.      return position; 
  24.  } 
  25.  
  26.  @Override 
  27.  public Component getComponent(int position, Component component, ComponentContainer componentContainer) { 
  28.      return getRootComponent(position); 
  29.  } 
  30.  
  31.  private Component getRootComponent(int position) { 
  32.  
  33.      //List item 布局組件 
  34.      Component rootComponent = LayoutScatter.getInstance(context) 
  35.              .parse(ResourceTable.Layout_list_item, nullfalse); 
  36.  
  37.      Text deviceName = (Text) rootComponent.findComponentById(ResourceTable.Id_bluetooth_device_name); 
  38.  
  39.      //藍牙設備名稱 
  40.      BluetoothDevice bluetoothDevice = bluetoothDeviceList.get(position); 
  41.      deviceName.setText(bluetoothDevice.getName()); 
  42.  
  43.      //設置點擊監(jiān)聽事件,開始配對 
  44.      rootComponent.setClickedListener(component -> { 
  45.          LogUtil.info("BluetoothItemProvider""startPair:" + bluetoothDevice.getAddress()); 
  46.          //表示對端設備未配對。 
  47.          if (bluetoothDevice.getPairState() == BluetoothRemoteDevice.PAIR_STATE_NONE) { 
  48.              //啟動與給定地址的藍牙設備配對。 
  49.              BluetoothPlugin.getInstance(context).startPair(bluetoothDevice.getAddress()); 
  50.          } 
  51.      }); 
  52.  
  53.      return rootComponent; 
  54.  } 
  55.  
  56.  /** 
  57.   * 更新藍牙設備列表 
  58.   * updates available Bluetooth devices in UI 
  59.   * 
  60.   * @param devices list of Bluetooth devices 
  61.   */ 
  62.  public void updateDeviceList(List<BluetoothDevice> devices) { 
  63.      bluetoothDeviceList = devices; 
  64.      notifyDataChanged(); 
  65.  } 

4.2.5 MainAbilitySlice.java 主能力頁面操作

a.首先是實現(xiàn)了幾個相關的接口

Component.ClickedListener 用于實現(xiàn)按鈕的點擊事件

BluetoothEventListener 用于實現(xiàn)藍牙事件通知的處理

CheckedStateChangedListener 用于實現(xiàn)switch開關的處理

  1. public class MainAbilitySlice extends AbilitySlice 
  2.     implements Component.ClickedListener, BluetoothEventListener, AbsButton.CheckedStateChangedListener { 

b.初始化工作

在onActive生命周期函數(shù)中

初始化藍牙插件/初始化容器列表/初始化組件/訂閱藍牙事件

  1. /** 
  2. * 初始化藍牙插件 
  3. */ 
  4. private void initializeBluetoothHost() { 
  5.   // 
  6.   BluetoothPlugin.getInstance(this).initializeBluetooth(this); 
  7.  
  8. private void initComponents() { 
  9.   //'開始發(fā)現(xiàn)' 按鈕,用來搜索附件的藍牙設備 
  10.   Button btnStartDiscovery = (Button) findComponentById(ResourceTable.Id_btn_start_discovery); 
  11.   //因為implements Component.ClickedListener 所以可以這樣寫 
  12.   btnStartDiscovery.setClickedListener(this); 
  13.  
  14.   initListContainer(); 
  15.   //藍牙狀態(tài)文本組件 
  16.   textBluetoothStatus = (Text) findComponentById(ResourceTable.Id_bluetooth_status); 
  17.  
  18.   //藍牙開關組件 
  19.   bluetoothSwitch = (Switch) findComponentById(ResourceTable.Id_bt_switch); 
  20.   //設置狀態(tài)監(jiān)聽事件 
  21.   bluetoothSwitch.setCheckedStateChangedListener(this); 
  22.  
  23.   //根據(jù)系統(tǒng)藍牙狀態(tài)設置開關 
  24.   updateBluetoothStatus(BluetoothPlugin.getInstance(this).getBluetoothStatus()); 
  25.  
  26.   //附件的藍牙設備容器列表 
  27.   containerLists = (DirectionalLayout) findComponentById(ResourceTable.Id_container_lists); 
  28.   //根據(jù)藍牙狀態(tài)控制是否顯示附件的藍牙設備容器列表 
  29.   containerLists.setVisibility(isBluetoothEnabled() ? Component.VISIBLE : Component.HIDE); 
  30.  
  31.   //環(huán)形進度條組件 
  32.   progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progressbar); 
  33.  
  34. /** 
  35. * 訂閱藍牙事件 
  36. */ 
  37. private void subscribeBluetoothEvents() { 
  38.   // 
  39.   BluetoothPlugin.getInstance(this).subscribeBluetoothEvents(); 
  40.  
  41. /** 
  42. * 初始化容器列表 
  43. */ 
  44. private void initListContainer() { 
  45.   ListContainer availableDevicesContainer = 
  46.       (ListContainer) findComponentById(ResourceTable.Id_list_available_devices); 
  47.  
  48.   //1.獲取可用的藍牙設備 
  49.   availableDevicesItemProvider = new BluetoothItemProvider(this, 
  50.       BluetoothPlugin.getInstance(this).getAvailableDevices()); 
  51.   //設置提供程序 
  52.   availableDevicesContainer.setItemProvider(availableDevicesItemProvider); 
  53.  
  54.   //2.獲取已配對的藍牙設備 
  55.   ListContainer pairedDevicesContainer = (ListContainer) findComponentById(ResourceTable.Id_list_paired_devices); 
  56.   pairedDevicesItemProvider = new BluetoothItemProvider(this, 
  57.       BluetoothPlugin.getInstance(this).getPairedDevices()); 
  58.   //設置提供程序 
  59.   pairedDevicesContainer.setItemProvider(pairedDevicesItemProvider); 
  60.  
  61. /** 
  62. * 更新藍牙狀態(tài)開關和文本 
  63. * @param bluetoothStatus 
  64. */ 
  65. private void updateBluetoothStatus(int bluetoothStatus) { 
  66.   LogUtil.info("MainAbilitySlice""updateBluetoothStatus:" + bluetoothStatus); 
  67.   //開關 
  68.   bluetoothSwitch.setChecked(isBluetoothEnabled()); 
  69.   //狀態(tài)文本 
  70.   textBluetoothStatus.setText(getBluetoothStatusString(bluetoothStatus)); 
  71.  
  72.  
  73. /** 
  74. * 顯示環(huán)形進度條 
  75. * 用定時器實現(xiàn)了一個進度條,遺憾的是有一定的卡頓 
  76. * @param isShow 
  77. */ 
  78. private void showProgressBar(boolean isShow) { 
  79.   LogUtil.info("MainAbilitySlice""isShow:" + isShow); 
  80.   LogUtil.info("MainAbilitySlice""timer=" + timer); 
  81.   if(isShow){ 
  82.       //顯示進度條 
  83.       progressBar.setVisibility(Component.VISIBLE); 
  84.       if(timer==null){ 
  85.           timer = new Timer(); 
  86.       } 
  87.       if(timerTask==null){ 
  88.           timerTask= new TimerTask() { 
  89.               @Override 
  90.               public void run() { 
  91.                   if(percent==10){ 
  92.                       percent=1; 
  93.                       progressBar.setProgressValue(0); 
  94.                   }else
  95.                       percent++; 
  96.                   } 
  97.                   LogUtil.info("MainAbilitySlice""percent:" + percent); 
  98.                   getContext().getUITaskDispatcher().asyncDispatch(new Runnable() { 
  99.                       @Override 
  100.                       public void run() { 
  101.                           progressBar.setProgressValue(percent*10); 
  102.                       } 
  103.                   }); 
  104.               } 
  105.           }; 
  106.           // 
  107.           timer.schedule(timerTask, 0, 1000); 
  108.       } 
  109.   }else { 
  110.       //隱藏進度條 
  111.       progressBar.setProgressValue(0); 
  112.       progressBar.setVisibility(Component.HIDE); 
  113.  
  114.       if(timer!=null){ 
  115.           LogUtil.info("MainAbilitySlice""timer set null"); 
  116.           timer.cancel(); 
  117.           timerTask.cancel(); 
  118.           timer=null
  119.           timerTask=null
  120.       } 
  121.   } 
  122.  
  123.  
  124. /** 
  125. * 獲取藍牙狀態(tài) 
  126. * @return 
  127. */ 
  128. private boolean isBluetoothEnabled() { 
  129.  
  130.   int status = BluetoothPlugin.getInstance(this).getBluetoothStatus(); 
  131.   LogUtil.info("isBluetoothEnabled""isBluetoothEnabled:"+status); 
  132.   return status == BluetoothHost.STATE_ON; 
  133.  
  134.  
  135. private String getBluetoothStatusString(int bluetoothStatus) { 
  136.   LogUtil.info("bluetoothStatus""bluetoothStatus:"+bluetoothStatus); 
  137.   switch (bluetoothStatus) { 
  138.  
  139.       case BluetoothHost.STATE_OFF: 
  140.  
  141.       case BluetoothHost.STATE_BLE_TURNING_OFF: 
  142.           //disabled 不可用 
  143.           return Constants.BT_DISABLED; 
  144.  
  145.       case BluetoothHost.STATE_TURNING_ON: 
  146.           //turning on 開啟 
  147.           return Constants.BT_TURNING_ON; 
  148.  
  149.       case BluetoothHost.STATE_ON: 
  150.           //enabled 可用的 
  151.           return Constants.BT_ENABLED; 
  152.  
  153.       case BluetoothHost.STATE_TURNING_OFF: 
  154.           //turning off 關閉 
  155.           return Constants.BT_TURNING_OFF; 
  156.  
  157.       default
  158.           //undefined 未定義 
  159.           return Constants.BT_UNDEFINED; 
  160.   } 

c.實現(xiàn)BluetoothEventListener接口相關函數(shù)

  1. @Override 
  2. public void updateAvailableDevices(List<BluetoothDevice> list) { 
  3.   //implements BluetoothEventListener 
  4.   //更新容器數(shù)據(jù) 
  5.   availableDevicesItemProvider.updateDeviceList(list); 
  6.  
  7. @Override 
  8. public void updatePairedDevices(List<BluetoothDevice> list) { 
  9.   //implements BluetoothEventListener 
  10.   //更新容器數(shù)據(jù) 
  11.   pairedDevicesItemProvider.updateDeviceList(list); 
  12.  
  13. @Override 
  14. public void notifyBluetoothStatusChanged(int bluetoothStatus) { 
  15.   LogUtil.info("notifyBluetoothStatusChanged""bluetoothStatus:"+bluetoothStatus); 
  16.   //藍牙狀態(tài)改變事件通知 
  17.   updateBluetoothStatus(bluetoothStatus); 
  18.  
  19. @Override 
  20. public void notifyDiscoveryState(boolean isStarted) { 
  21.   //藍牙發(fā)現(xiàn)狀態(tài)的事件通知 
  22.   showProgressBar(isStarted); 

d.實現(xiàn)CheckedStateChangedListener接口相關函數(shù)

  1. @Override 
  2. public void onCheckedChanged(AbsButton absButton, boolean isChecked) { 
  3.   //開關狀態(tài)改變事件觸發(fā) 
  4.   if (absButton.getId() == ResourceTable.Id_bt_switch && containerLists != null) { 
  5.       if (isChecked) { 
  6.           LogUtil.info("onCheckedChanged""enableBluetooth"); 
  7.           //開啟藍牙 
  8.           BluetoothPlugin.getInstance(this).enableBluetooth(); 
  9.           containerLists.setVisibility(Component.VISIBLE); 
  10.       } else { 
  11.           //關閉藍牙 
  12.           BluetoothPlugin.getInstance(this).disableBluetooth(); 
  13.           containerLists.setVisibility(Component.HIDE); 
  14.  
  15.  
  16.       } 
  17.   } 

e.實現(xiàn)ClickedListener接口相關函數(shù),開始發(fā)現(xiàn)藍牙

  1. @Override 
  2. public void onClick(Component component) { 
  3.   LogUtil.info("MainAbilitySlice""startBtScan..."); 
  4.   //開始發(fā)現(xiàn)  掃描藍牙設備 
  5.   if (component.getId() == ResourceTable.Id_btn_start_discovery) { 
  6.       LogUtil.info("MainAbilitySlice""startBtScan..."); 
  7.       BluetoothPlugin.getInstance(this).startBtScan(); 
  8.   } 

5.完整代碼

附件直接下載

想了解更多內(nèi)容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術社區(qū)

https://harmonyos.51cto.com

 

責任編輯:jianghua 來源: 鴻蒙社區(qū)
相關推薦

2021-09-17 14:43:54

鴻蒙HarmonyOS應用

2021-09-24 09:25:01

鴻蒙HarmonyOS應用

2021-08-17 10:20:14

鴻蒙HarmonyOS應用

2021-09-15 14:55:49

鴻蒙HarmonyOS應用

2015-02-27 16:03:26

Android源碼Bluetooth_4BLE藍牙通信

2021-11-23 09:58:35

鴻蒙HarmonyOS應用

2021-07-08 09:42:04

鴻蒙HarmonyOS應用

2021-11-02 10:10:49

鴻蒙HarmonyOS應用

2021-12-10 15:06:56

鴻蒙HarmonyOS應用

2021-12-02 10:11:44

鴻蒙HarmonyOS應用

2021-11-30 14:51:11

鴻蒙HarmonyOS應用

2021-07-29 14:03:35

鴻蒙HarmonyOS應用

2021-08-24 15:13:06

鴻蒙HarmonyOS應用

2021-06-02 00:15:41

C# PC藍牙

2023-04-17 16:10:14

鴻蒙藍牙

2021-03-26 14:00:27

物聯(lián)網(wǎng)藍牙低功耗

2021-11-07 14:29:13

ChromeAPI 藍牙

2022-06-07 10:40:05

藍牙鴻蒙

2009-09-27 13:00:56

Hibernate S

2014-03-14 10:16:30

ModernWindows 8.1
點贊
收藏

51CTO技術棧公眾號