Android 9.0 藍(lán)牙功能之一:藍(lán)牙設(shè)置
本章節(jié)記錄如何構(gòu)建藍(lán)牙設(shè)置。
注意藍(lán)牙應(yīng)用必須是 System App。
主要流程
LocalBluetoothManager 是操作藍(lán)牙的主要入口。
1.通過 LocalBluetoothManager,可以獲取到LocalBluetoothAdapter;CachedBluetoothDeviceManager;BluetoothEventManager、LocalBluetoothProfileManager。
2.通過 BluetoothEventManager.registerCallback 注冊(cè)回調(diào),就可以
監(jiān)聽藍(lán)牙狀態(tài)變化、設(shè)備搜索、連接狀態(tài)等信息。
3.注冊(cè)BluetoothCallback.onBluetoothStateChanged 回調(diào)即可監(jiān)聽藍(lán)牙開關(guān)狀態(tài)。
可以通過LocalBluetoothAdapter.enable()打開藍(lán)牙。
4.注冊(cè)BluetoothCallback.onScanningStateChanged來監(jiān)聽藍(lán)牙搜索狀態(tài),
當(dāng)調(diào)用LoalBluetoothAdapter.startScanning 開始搜索后搜索到的設(shè)備通過
BluetoothCallback.onDeviceAdded 回調(diào)給 App。
5.最后通過 CachedBluetoothDevice.connect發(fā)起連接搜索到的指定設(shè)備。
相關(guān)代碼
添加藍(lán)牙相關(guān)權(quán)限:
AndroidManifest.xml :
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
初始化藍(lán)牙相關(guān)接口
//獲取藍(lán)牙相關(guān)對(duì)象
mLocalBluetoothManager = LocalBluetoothManager.getInstance(context,mOnInitCallback);
mCachedDeviceManager = mLocalBluetoothManager.getCachedDeviceManager();
mBluetoothEventManager = mLocalBluetoothManager.getEventManager();
mBluetoothProfileManager = mLocalBluetoothManager.getProfileManager();
//注冊(cè)回調(diào)
mBluetoothEventManager.registerCallback(mBluetoothCallback);
mBluetoothProfileManager.addServiceListener(mServiceListener);
實(shí)現(xiàn) ServiceListener,以監(jiān)聽 Profile 相關(guān)接口文章來源:http://www.zghlxwxcb.cn/news/detail-423309.html
LocalBluetoothProfileManager.ServiceListener mServiceListener = new LocalBluetoothProfileManager.ServiceListener() {
void onServiceConnected() {
//藍(lán)牙已經(jīng)打開,可以調(diào)用各 Profile 的接口了,比如可以獲取連接狀態(tài),連接藍(lán)牙設(shè)備等。
}
void onServiceDisconnected() {
//藍(lán)牙已經(jīng)關(guān)閉
}
};
監(jiān)聽藍(lán)牙各狀態(tài)變化,至于設(shè)備的連接或者斷開主要通過CachedBluetoothDevice對(duì)象操作。文章來源地址http://www.zghlxwxcb.cn/news/detail-423309.html
BluetoothCallback mBluetoothCallback = new BluetoothCallback() {
void onBluetoothStateChanged(int bluetoothState) {
//藍(lán)牙開關(guān)狀態(tài)變化
}
void onScanningStateChanged(boolean started) {
//藍(lán)牙搜索狀態(tài)變化
}
void onDeviceAdded(CachedBluetoothDevice cachedDevice) {
//搜索到新設(shè)備
}
void onDeviceDeleted(CachedBluetoothDevice cachedDevice) {
//配對(duì)的設(shè)備被移除
}
void onDeviceBondStateChanged(CachedBluetoothDevice cachedDevice, int bondState) {
//設(shè)備配對(duì)狀態(tài)變化
}
void onConnectionStateChanged(CachedBluetoothDevice cachedDevice, int state) {
//設(shè)備連接狀態(tài)變化
}
void onActiveDeviceChanged(CachedBluetoothDevice activeDevice, int bluetoothProfile) {
//活動(dòng)設(shè)備變化
}
void onProfileConnectionStateChanged(CachedBluetoothDevice cachedDevice) {
//Profile協(xié)議連接狀態(tài)變化(a2db;hdcp)
}
};
到了這里,關(guān)于Android 9.0 藍(lán)牙功能之一:藍(lán)牙設(shè)置的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!