標籤:
隨著近兩年可穿戴式產品逐漸進入人們的生活,藍芽開發也成為了Android開發的一個重要模組,下面我們就來說一說藍芽的這些API。
1.藍芽開發有兩個主要的API:
BuletoothAdapter:本地藍芽的適配器,也就是說當前應用程式所啟動並執行Android裝置上的藍芽
BuletoothDevice : 遠端藍芽適配器,也就是說你要串連的Android裝置的適配器。
2.藍芽許可權 :
android.permission.BLUETOOTH : 允許程式串連到已配對的藍牙裝置, 請求串連/接收串連/傳輸資料需要改許可權, 主要用於對配對後進行操作;
android.permission.BLUETOOTH_ADMIN : 允許程式發現和配對藍牙裝置, 該許可權用來管理藍牙裝置, 有了這個許可權, 應用才能使用原生藍牙裝置, 主要用於對配對前的操作;
優先順序 : BLUETOOTH許可權是BLUETOOTH_ADMIN許可權的前提, 如果沒有BLUETOOTH許可權, 就不能使用BLUETOOTH_ADMIN許可權;
3.藍芽狀態值:
藍芽關閉 : int STATE_OFF , 值為10, 藍芽模組處於關閉狀態;
藍芽開啟中 : int STATE_TURNING_ON , 值為11, 藍芽模組正在開啟;
藍芽開啟 : int STATE_ON , 值為12, 藍芽模組處於開啟狀態;
藍芽開啟中 : int STATE_TURNING_OFF , 值為13, 藍芽模組正在關閉;
4.藍芽相關的廣播:
開關狀態改變:
BluetoothAdapter.ACTION_STATE_CHANGE:
可以通過intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)擷取當前藍芽改變的狀態。
搜尋到附近可用裝置:
BluetoothDevice.ACTION_FOUND:
可以通過intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 擷取當前搜尋到的遠程裝置。
配對請求:
BluetoothDevice.ACTION_PAIRING_REQUEST
配對狀態改變:
BluetoothDevice.ACTION_PAIRING_REQUEST:
5.常用方法:
開啟/關閉 藍芽:
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); //擷取本地藍芽執行個體
if (!mAdapter.isEnabled()){
mAdapter.enable(); //開啟藍芽
}else{
mAdapter.enable(); //關閉藍芽
}
設定藍芽可見度:
可見:adapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
不可見:adapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);
設定可見度逾時時間: adapter.setDiscoverableTimeout(BLUETOOTH_DSCOVERABLE_TIME);
開始 / 停止 掃描附近的裝置:
mAdapter.startDiscovery(); //開始掃描
mAdapter.startDiscovery(); //停止掃描
擷取藍芽基本資料:
MAC地址:mAdapter.getAddress();
名稱: mAdapter.getName();
與遠程裝置配對:
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
Android 藍芽API詳解