HarmonyOS Sample之Bluetooth傳統(tǒng)藍(lán)牙的使用
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
1.介紹
本示例演示了如何對藍(lán)牙進(jìn)行基本操作,
傳統(tǒng)藍(lán)牙本機(jī)管理:
主要是針對藍(lán)牙本機(jī)的基本操作,包括:打開和關(guān)閉藍(lán)牙、設(shè)置和獲取本機(jī)藍(lán)牙名稱、掃描和取消掃描周邊藍(lán)牙設(shè)備、獲取本機(jī)藍(lán)牙profile對其他設(shè)備的連接狀態(tài)、獲取本機(jī)藍(lán)牙已配對的藍(lán)牙設(shè)備列表。
傳統(tǒng)藍(lán)牙遠(yuǎn)端管理操作:
主要是針對遠(yuǎn)端藍(lán)牙設(shè)備的基本操作,包括:獲取遠(yuǎn)端藍(lán)牙設(shè)備地址、類型、名稱和配對狀態(tài),以及向遠(yuǎn)端設(shè)備發(fā)起配對。
傳統(tǒng)藍(lán)牙和BLE的的概念請參考 藍(lán)牙開發(fā)概述
還有一個小知識點,
調(diào)用藍(lán)牙的打開接口需要ohos.permission.USE_BLUETOOTH權(quán)限,
調(diào)用藍(lán)牙掃描接口需要ohos.permission.LOCATION權(quán)限和ohos.permission.DISCOVER_BLUETOOTH權(quán)限。
2.搭建環(huán)境
安裝DevEco Studio,詳情請參考DevEco Studio下載。
設(shè)置DevEco Studio開發(fā)環(huán)境,DevEco Studio開發(fā)環(huán)境需要依賴于網(wǎng)絡(luò)環(huán)境,需要連接上網(wǎng)絡(luò)才能確保工具的正常使用,可以根據(jù)如下兩種情況來配置開發(fā)環(huán)境:
如果可以直接訪問Internet,只需進(jìn)行下載HarmonyOS SDK操作。
如果網(wǎng)絡(luò)不能直接訪問Internet,需要通過代理服務(wù)器才可以訪問,請參考配置開發(fā)環(huán)境。
下載源碼后,使用DevEco Studio 打開項目,模擬器運(yùn)行即可。
真機(jī)運(yùn)行需要將config.json中的buddleName修改為自己的,如果沒有請到AGC上進(jìn)行配置,參見 使用模擬器進(jìn)行調(diào)試 。
3.代碼結(jié)構(gòu)

4.實例講解
4.1.界面布局
布局效果


4.2.后臺代碼
4.2.1 涉及的相關(guān)類
SDK提供的核心類:
BluetoothHost.java//藍(lán)牙主機(jī),可以管理藍(lán)牙,提供了藍(lán)牙的基本操作,打開/關(guān)閉/獲取狀態(tài)等。
BluetoothRemoteDevice.java//藍(lán)牙對象,用于建立與對端設(shè)備的連接并查詢名稱、設(shè)備類型和配對狀態(tài)等信息。
自定義的類:
BluetoothItemProvider.java//藍(lán)牙設(shè)備列表項提供程序
BluetoothEventListener.java//藍(lán)牙事件監(jiān)聽接口
BluetoothPlugin.java//藍(lán)牙插件
BluetoothDevice.java//藍(lán)牙對象簡易模型
4.2.2 BluetoothPlugin.java 藍(lán)牙插件提供的功能
a.初始化BluetoothHost藍(lán)牙主機(jī)對象getDefaultHost
- /**
- * 初始化藍(lán)牙主機(jī)對象和監(jiān)聽器
- * Initializes the Bluetooth Host on device.
- * @param eventListener interface to update the Bluwettoth events
- */
- public void initializeBluetooth(BluetoothEventListener eventListener) {
- bluetoothEventListener = eventListener;
- btHost = BluetoothHost.getDefaultHost(mainSliceContext);
- LogUtil.info(TAG, "initializeBluetooth, btHost:"+btHost);
- }
b.開啟/關(guān)閉藍(lán)牙/獲取藍(lán)牙狀態(tài)enableBt/disableBt/getBtState
- /**
- * 開啟藍(lán)牙
- * 低功耗藍(lán)牙(BLE ,Bluetooth Low Energy),LE是2010年才提出的
- * 經(jīng)典藍(lán)牙(classic Bluetooth),包括BR,EDR和HS(AMP)三種模式
- * Enables the Bluetooth on device.
- */
- public void enableBluetooth() {
- LogUtil.info("enableBluetooth", "getBtState:"+btHost.getBtState());
- //獲取藍(lán)牙主機(jī)的狀態(tài)
- if (btHost.getBtState() == STATE_OFF ||
- btHost.getBtState() == STATE_TURNING_OFF ||
- btHost.getBtState() ==STATE_BLE_ON) {
- LogUtil.info("enableBluetooth", "enableBt:"+btHost.getBtState());
- //開啟藍(lán)牙
- btHost.enableBt();
- }
- //事件通知藍(lán)牙狀態(tài)發(fā)生改變
- bluetoothEventListener.notifyBluetoothStatusChanged(btHost.getBtState());
- }
- /**
- * 關(guān)閉藍(lán)牙
- * Disables the Bluetooth on device.
- */
- public void disableBluetooth() {
- if (btHost.getBtState() == STATE_ON || btHost.getBtState() == STATE_TURNING_ON) {
- btHost.disableBt();
- }
- bluetoothEventListener.notifyBluetoothStatusChanged(btHost.getBtState());
- }
- /**
- * 獲取藍(lán)牙狀態(tài)
- * Obtains the status of the Bluetooth on device.
- * @return status of Bluetooth on device
- */
- public int getBluetoothStatus() {
- LogUtil.info("getBluetoothStatus", "getBluetoothStatus:"+btHost.getBtState());
- //獲取藍(lán)牙狀態(tài)
- return btHost.getBtState();
- }
c.開始藍(lán)牙發(fā)現(xiàn)startBtDiscovery
還要注意的是藍(lán)牙發(fā)現(xiàn)操作需要申請位置權(quán)限。
- /**
- * 開始藍(lán)牙發(fā)現(xiàn)
- * Scans the currently available bluetooth devices
- */
- public void startBtDiscovery() {
- if (!btHost.isBtDiscovering()) {
- //開始發(fā)現(xiàn)設(shè)備,大約需要12.8s
- btHost.startBtDiscovery();
- }
- }
- /**
- *判斷是否有權(quán)限
- */
- private boolean hasPermission() {
- return mainSliceContext.verifySelfPermission(Constants.PERM_LOCATION) == IBundleManager.PERMISSION_GRANTED;
- }
- /**
- * 啟動藍(lán)牙掃描
- * Scans the currently available bluetooth devices
- */
- public void startBtScan() {
- LogUtil.info("startBtScan", "getBtState:"+btHost.getBtState());
- int btStatus = btHost.getBtState();
- if (btStatus == STATE_ON) {
- if (hasPermission()) {
- startBtDiscovery();
- } else {
- requestPermission();
- }
- }
- }
d.藍(lán)牙設(shè)備配對及獲取已配對的設(shè)備列表startPair/getPairedDevices
- /**
- * 啟動與給定地址的藍(lán)牙設(shè)備配對。
- * initiate pairing with bluetooth device of given address.
- * @param pairAddress address of the bluetooth device
- */
- public void startPair(String pairAddress) {
- Optional<BluetoothRemoteDevice> optBluetoothDevice = getSelectedDevice(pairAddress);
- optBluetoothDevice.ifPresent(BluetoothRemoteDevice::startPair);
- }
- /**
- * 獲取要配對的設(shè)備
- * @param pairAddress
- * @return
- */
- private Optional<BluetoothRemoteDevice> getSelectedDevice(String pairAddress) {
- if (pairAddress != null && !pairAddress.isEmpty()) {
- for (BluetoothRemoteDevice device : availableDevices) {
- if (device.getDeviceAddr().equals(pairAddress)) {
- return Optional.ofNullable(device);
- }
- }
- }
- return Optional.empty();
- }
- /**
- * 獲取已配對的藍(lán)牙設(shè)備列表
- * Obtains the paired Bluetooth device list.
- * @return paired Bluetooth devices
- */
- public List<BluetoothDevice> getPairedDevices() {
- //btHost.getPairedDevices()
- Set<BluetoothRemoteDevice> pairedDevices = new HashSet<>(btHost.getPairedDevices());
- return getBluetoothDevices(pairedDevices);
- }
e.藍(lán)牙事件的訂閱/取消 及 相關(guān)事件的處理
在處理藍(lán)牙事件的同時,通過BluetoothEventListener通知MainAbilitySlice。
- /**
- * 訂閱藍(lán)牙事件
- * Subscribe for Events of Bluetooth using CommonEvents
- */
- public void subscribeBluetoothEvents() {
- MatchingSkills matchingSkills = new MatchingSkills();
- //表示藍(lán)牙狀態(tài)改變時上報的事件。
- matchingSkills.addEvent(BluetoothHost.EVENT_HOST_STATE_UPDATE);
- //指示藍(lán)牙掃描開始時報告的事件。
- matchingSkills.addEvent(BluetoothHost.EVENT_HOST_DISCOVERY_STARTED);
- //指示藍(lán)牙掃描完成時報告的事件。
- matchingSkills.addEvent(BluetoothHost.EVENT_HOST_DISCOVERY_FINISHED);
- //表示發(fā)現(xiàn)遠(yuǎn)程藍(lán)牙設(shè)備時上報的事件。
- matchingSkills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED);
- //遠(yuǎn)程藍(lán)牙設(shè)備配對時上報的事件。
- matchingSkills.addEvent(BluetoothRemoteDevice.EVENT_DEVICE_PAIR_STATE);
- //用于創(chuàng)建 CommonEventSubscriber 實例并傳遞 subscribeInfo 參數(shù)的構(gòu)造函數(shù)。
- CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
- //訂閱者
- commonEventSubscriber = new CommonEventSubscriber(subscribeInfo) {
- @Override
- public void onReceiveEvent(CommonEventData commonEventData) {
- Intent intent = commonEventData.getIntent();
- handleIntent(intent);
- }
- };
- try {
- //完成訂閱
- CommonEventManager.subscribeCommonEvent(commonEventSubscriber);
- } catch (RemoteException e) {
- LogUtil.error(TAG, "RemoteException while subscribe bluetooth events.");
- }
- }
- /**
- * 取消訂閱藍(lán)牙事件
- * UnSubscribe for Bluetooth Events
- */
- public void unSubscribeBluetoothEvents() {
- if (commonEventSubscriber != null) {
- try {
- CommonEventManager.unsubscribeCommonEvent(commonEventSubscriber);
- } catch (RemoteException e) {
- LogUtil.error(TAG, "RemoteException while unsubscribing bluetooth events.");
- }
- commonEventSubscriber = null;
- }
- }
- private void handleIntent(Intent intent) {
- if (intent == null) {
- return;
- }
- String action = intent.getAction();
- switch (action) {
- //狀態(tài)更新
- case BluetoothHost.EVENT_HOST_STATE_UPDATE:
- handleHostStateUpdate();
- break;
- //掃描開始
- case BluetoothHost.EVENT_HOST_DISCOVERY_STARTED:
- handleDeviceDiscoveryState(true);
- break;
- //表示發(fā)現(xiàn)遠(yuǎn)程藍(lán)牙設(shè)備時上報的事件。
- case BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED:
- handleBluetoothDeviceDiscovered(intent);
- break;
- // 掃描完成
- case BluetoothHost.EVENT_HOST_DISCOVERY_FINISHED:
- handleDeviceDiscoveryState(false);
- break;
- //表示遠(yuǎn)程藍(lán)牙設(shè)備配對時上報的事件。
- case BluetoothRemoteDevice.EVENT_DEVICE_PAIR_STATE:
- handleDevicePairState(intent);
- break;
- default:
- LogUtil.info(TAG, "Action not handled : " + action);
- }
- }
- private void handleDevicePairState(Intent intent) {
- BluetoothRemoteDevice btRemoteDevice = intent.getSequenceableParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);
- if (btRemoteDevice.getPairState() == BluetoothRemoteDevice.PAIR_STATE_PAIRED) {
- //更新2個設(shè)備列表
- updateAvailableDeviceList(btRemoteDevice);
- updatePairedDeviceList();
- }
- }
- private void handleDeviceDiscoveryState(boolean isStarted) {
- //處理掃描狀態(tài)變化事件通知
- bluetoothEventListener.notifyDiscoveryState(isStarted);
- }
- /**
- * 處理藍(lán)牙狀態(tài)變化通知
- */
- private void handleHostStateUpdate() {
- int status = getBluetoothStatus();
- bluetoothEventListener.notifyBluetoothStatusChanged(status);
- }
- /**
- * 處理藍(lán)牙發(fā)現(xiàn)事件
- * @param intent
- */
- private void handleBluetoothDeviceDiscovered(Intent intent) {
- BluetoothRemoteDevice btRemoteDevice =
- intent.getSequenceableParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);
- //未配對的設(shè)備
- if (btRemoteDevice.getPairState() != BluetoothRemoteDevice.PAIR_STATE_PAIRED) {
- //發(fā)現(xiàn)后添加到可用的藍(lán)牙設(shè)備
- availableDevices.add(btRemoteDevice);
- }
- bluetoothEventListener.updateAvailableDevices(getAvailableDevices());
- }
- /**
- * 更新可用設(shè)備列表
- * @param remoteDevice
- */
- private void updateAvailableDeviceList(BluetoothRemoteDevice remoteDevice) {
- //移除以配對的藍(lán)牙
- availableDevices.removeIf(device -> device.getDeviceAddr().equals(remoteDevice.getDeviceAddr()));
- bluetoothEventListener.updateAvailableDevices(getAvailableDevices());
- }
- private void updatePairedDeviceList() {
- //刷新已配對的藍(lán)牙列表
- bluetoothEventListener.updatePairedDevices(getPairedDevices());
- }
- public List<BluetoothDevice> getAvailableDevices() {
- return getBluetoothDevices(availableDevices);
- }
- /**
- * 獲取已配對的藍(lán)牙設(shè)備列表
- * Obtains the paired Bluetooth device list.
- * @return paired Bluetooth devices
- */
- public List<BluetoothDevice> getPairedDevices() {
- //btHost.getPairedDevices()
- Set<BluetoothRemoteDevice> pairedDevices = new HashSet<>(btHost.getPairedDevices());
- return getBluetoothDevices(pairedDevices);
- }
- private List<BluetoothDevice> getBluetoothDevices(Set<BluetoothRemoteDevice> remoteDeviceList) {
- List<BluetoothDevice> btDevicesList = new ArrayList<>();
- if (remoteDeviceList != null) {
- //
- btDevicesList = remoteDeviceList.stream().map(BluetoothDevice::new).collect(Collectors.toList());
- }
- return btDevicesList;
- }
4.2.3 BluetoothEventListener.java 自定義的藍(lán)牙事件監(jiān)聽器接口
- public interface BluetoothEventListener {
- void updateAvailableDevices(List<BluetoothDevice> bluetoothDevice);
- void updatePairedDevices(List<BluetoothDevice> bluetoothDevice);
- void notifyBluetoothStatusChanged(int bluetoothStatus);
- void notifyDiscoveryState(boolean isStarted);
- }
4.2.4 BluetoothItemProvider.java 藍(lán)牙設(shè)備列表提供程序
這個可以作為一個標(biāo)準(zhǔn)件了,每個ListContainer都可以用它,包括了列表的通用操作,像數(shù)據(jù)更新,點擊事件等。
- public class BluetoothItemProvider extends BaseItemProvider {
- private final AbilityContext context;
- private List<BluetoothDevice> bluetoothDeviceList;
- public BluetoothItemProvider(AbilityContext context, List<BluetoothDevice> itemList) {
- this.context = context;
- bluetoothDeviceList = itemList;
- }
- @Override
- public int getCount() {
- return bluetoothDeviceList.size();
- }
- @Override
- public Object getItem(int position) {
- return bluetoothDeviceList.get(position);
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
- return getRootComponent(position);
- }
- private Component getRootComponent(int position) {
- //List item 布局組件
- Component rootComponent = LayoutScatter.getInstance(context)
- .parse(ResourceTable.Layout_list_item, null, false);
- Text deviceName = (Text) rootComponent.findComponentById(ResourceTable.Id_bluetooth_device_name);
- //藍(lán)牙設(shè)備名稱
- BluetoothDevice bluetoothDevice = bluetoothDeviceList.get(position);
- deviceName.setText(bluetoothDevice.getName());
- //設(shè)置點擊監(jiān)聽事件,開始配對
- rootComponent.setClickedListener(component -> {
- LogUtil.info("BluetoothItemProvider", "startPair:" + bluetoothDevice.getAddress());
- //表示對端設(shè)備未配對。
- if (bluetoothDevice.getPairState() == BluetoothRemoteDevice.PAIR_STATE_NONE) {
- //啟動與給定地址的藍(lán)牙設(shè)備配對。
- BluetoothPlugin.getInstance(context).startPair(bluetoothDevice.getAddress());
- }
- });
- return rootComponent;
- }
- /**
- * 更新藍(lán)牙設(shè)備列表
- * updates available Bluetooth devices in UI
- *
- * @param devices list of Bluetooth devices
- */
- public void updateDeviceList(List<BluetoothDevice> devices) {
- bluetoothDeviceList = devices;
- notifyDataChanged();
- }
- }
4.2.5 MainAbilitySlice.java 主能力頁面操作
a.首先是實現(xiàn)了幾個相關(guān)的接口
Component.ClickedListener 用于實現(xiàn)按鈕的點擊事件
BluetoothEventListener 用于實現(xiàn)藍(lán)牙事件通知的處理
CheckedStateChangedListener 用于實現(xiàn)switch開關(guān)的處理
- public class MainAbilitySlice extends AbilitySlice
- implements Component.ClickedListener, BluetoothEventListener, AbsButton.CheckedStateChangedListener {
b.初始化工作
在onActive生命周期函數(shù)中
初始化藍(lán)牙插件/初始化容器列表/初始化組件/訂閱藍(lán)牙事件
- /**
- * 初始化藍(lán)牙插件
- */
- private void initializeBluetoothHost() {
- //
- BluetoothPlugin.getInstance(this).initializeBluetooth(this);
- }
- private void initComponents() {
- //'開始發(fā)現(xiàn)' 按鈕,用來搜索附件的藍(lán)牙設(shè)備
- Button btnStartDiscovery = (Button) findComponentById(ResourceTable.Id_btn_start_discovery);
- //因為implements Component.ClickedListener 所以可以這樣寫
- btnStartDiscovery.setClickedListener(this);
- initListContainer();
- //藍(lán)牙狀態(tài)文本組件
- textBluetoothStatus = (Text) findComponentById(ResourceTable.Id_bluetooth_status);
- //藍(lán)牙開關(guān)組件
- bluetoothSwitch = (Switch) findComponentById(ResourceTable.Id_bt_switch);
- //設(shè)置狀態(tài)監(jiān)聽事件
- bluetoothSwitch.setCheckedStateChangedListener(this);
- //根據(jù)系統(tǒng)藍(lán)牙狀態(tài)設(shè)置開關(guān)
- updateBluetoothStatus(BluetoothPlugin.getInstance(this).getBluetoothStatus());
- //附件的藍(lán)牙設(shè)備容器列表
- containerLists = (DirectionalLayout) findComponentById(ResourceTable.Id_container_lists);
- //根據(jù)藍(lán)牙狀態(tài)控制是否顯示附件的藍(lán)牙設(shè)備容器列表
- containerLists.setVisibility(isBluetoothEnabled() ? Component.VISIBLE : Component.HIDE);
- //環(huán)形進(jìn)度條組件
- progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progressbar);
- }
- /**
- * 訂閱藍(lán)牙事件
- */
- private void subscribeBluetoothEvents() {
- //
- BluetoothPlugin.getInstance(this).subscribeBluetoothEvents();
- }
- /**
- * 初始化容器列表
- */
- private void initListContainer() {
- ListContainer availableDevicesContainer =
- (ListContainer) findComponentById(ResourceTable.Id_list_available_devices);
- //1.獲取可用的藍(lán)牙設(shè)備
- availableDevicesItemProvider = new BluetoothItemProvider(this,
- BluetoothPlugin.getInstance(this).getAvailableDevices());
- //設(shè)置提供程序
- availableDevicesContainer.setItemProvider(availableDevicesItemProvider);
- //2.獲取已配對的藍(lán)牙設(shè)備
- ListContainer pairedDevicesContainer = (ListContainer) findComponentById(ResourceTable.Id_list_paired_devices);
- pairedDevicesItemProvider = new BluetoothItemProvider(this,
- BluetoothPlugin.getInstance(this).getPairedDevices());
- //設(shè)置提供程序
- pairedDevicesContainer.setItemProvider(pairedDevicesItemProvider);
- }
- /**
- * 更新藍(lán)牙狀態(tài)開關(guān)和文本
- * @param bluetoothStatus
- */
- private void updateBluetoothStatus(int bluetoothStatus) {
- LogUtil.info("MainAbilitySlice", "updateBluetoothStatus:" + bluetoothStatus);
- //開關(guān)
- bluetoothSwitch.setChecked(isBluetoothEnabled());
- //狀態(tài)文本
- textBluetoothStatus.setText(getBluetoothStatusString(bluetoothStatus));
- }
- /**
- * 顯示環(huán)形進(jìn)度條
- * 用定時器實現(xiàn)了一個進(jìn)度條,遺憾的是有一定的卡頓
- * @param isShow
- */
- private void showProgressBar(boolean isShow) {
- LogUtil.info("MainAbilitySlice", "isShow:" + isShow);
- LogUtil.info("MainAbilitySlice", "timer=" + timer);
- if(isShow){
- //顯示進(jìn)度條
- progressBar.setVisibility(Component.VISIBLE);
- if(timer==null){
- timer = new Timer();
- }
- if(timerTask==null){
- timerTask= new TimerTask() {
- @Override
- public void run() {
- if(percent==10){
- percent=1;
- progressBar.setProgressValue(0);
- }else{
- percent++;
- }
- LogUtil.info("MainAbilitySlice", "percent:" + percent);
- getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
- @Override
- public void run() {
- progressBar.setProgressValue(percent*10);
- }
- });
- }
- };
- //
- timer.schedule(timerTask, 0, 1000);
- }
- }else {
- //隱藏進(jìn)度條
- progressBar.setProgressValue(0);
- progressBar.setVisibility(Component.HIDE);
- if(timer!=null){
- LogUtil.info("MainAbilitySlice", "timer set null");
- timer.cancel();
- timerTask.cancel();
- timer=null;
- timerTask=null;
- }
- }
- }
- /**
- * 獲取藍(lán)牙狀態(tài)
- * @return
- */
- private boolean isBluetoothEnabled() {
- int status = BluetoothPlugin.getInstance(this).getBluetoothStatus();
- LogUtil.info("isBluetoothEnabled", "isBluetoothEnabled:"+status);
- return status == BluetoothHost.STATE_ON;
- }
- private String getBluetoothStatusString(int bluetoothStatus) {
- LogUtil.info("bluetoothStatus", "bluetoothStatus:"+bluetoothStatus);
- switch (bluetoothStatus) {
- case BluetoothHost.STATE_OFF:
- case BluetoothHost.STATE_BLE_TURNING_OFF:
- //disabled 不可用
- return Constants.BT_DISABLED;
- case BluetoothHost.STATE_TURNING_ON:
- //turning on 開啟
- return Constants.BT_TURNING_ON;
- case BluetoothHost.STATE_ON:
- //enabled 可用的
- return Constants.BT_ENABLED;
- case BluetoothHost.STATE_TURNING_OFF:
- //turning off 關(guān)閉
- return Constants.BT_TURNING_OFF;
- default:
- //undefined 未定義
- return Constants.BT_UNDEFINED;
- }
- }
c.實現(xiàn)BluetoothEventListener接口相關(guān)函數(shù)
- @Override
- public void updateAvailableDevices(List<BluetoothDevice> list) {
- //implements BluetoothEventListener
- //更新容器數(shù)據(jù)
- availableDevicesItemProvider.updateDeviceList(list);
- }
- @Override
- public void updatePairedDevices(List<BluetoothDevice> list) {
- //implements BluetoothEventListener
- //更新容器數(shù)據(jù)
- pairedDevicesItemProvider.updateDeviceList(list);
- }
- @Override
- public void notifyBluetoothStatusChanged(int bluetoothStatus) {
- LogUtil.info("notifyBluetoothStatusChanged", "bluetoothStatus:"+bluetoothStatus);
- //藍(lán)牙狀態(tài)改變事件通知
- updateBluetoothStatus(bluetoothStatus);
- }
- @Override
- public void notifyDiscoveryState(boolean isStarted) {
- //藍(lán)牙發(fā)現(xiàn)狀態(tài)的事件通知
- showProgressBar(isStarted);
- }
d.實現(xiàn)CheckedStateChangedListener接口相關(guān)函數(shù)
- @Override
- public void onCheckedChanged(AbsButton absButton, boolean isChecked) {
- //開關(guān)狀態(tài)改變事件觸發(fā)
- if (absButton.getId() == ResourceTable.Id_bt_switch && containerLists != null) {
- if (isChecked) {
- LogUtil.info("onCheckedChanged", "enableBluetooth");
- //開啟藍(lán)牙
- BluetoothPlugin.getInstance(this).enableBluetooth();
- containerLists.setVisibility(Component.VISIBLE);
- } else {
- //關(guān)閉藍(lán)牙
- BluetoothPlugin.getInstance(this).disableBluetooth();
- containerLists.setVisibility(Component.HIDE);
- }
- }
- }
e.實現(xiàn)ClickedListener接口相關(guān)函數(shù),開始發(fā)現(xiàn)藍(lán)牙
- @Override
- public void onClick(Component component) {
- LogUtil.info("MainAbilitySlice", "startBtScan...");
- //開始發(fā)現(xiàn) 掃描藍(lán)牙設(shè)備
- if (component.getId() == ResourceTable.Id_btn_start_discovery) {
- LogUtil.info("MainAbilitySlice", "startBtScan...");
- BluetoothPlugin.getInstance(this).startBtScan();
- }
- }
5.完整代碼
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)