android藍芽開發 藍芽裝置的查詢和連線
阿新 • • 發佈:2019-02-05
Android對於藍芽開發從2.0版本的sdk才開始支援,而且模擬器不支援,測試至少需要兩部手機,所以制約了很多技術人員的開發。 1. 首先,要操作藍芽,先要在AndroidManifest.xml里加入許可權 // 管理藍芽裝置的許可權 <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /> // 使用藍芽裝置的許可權 <uses-permissionandroid:name="android.permission.BLUETOOTH" /> 2.開啟藍芽 獲得藍芽介面卡(android.bluetooth.BluetoothAdapter),檢查該裝置是否支援藍芽,如果支援,就開啟藍芽。 [java] // 檢查裝置是否支援藍芽 adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { // 裝置不支援藍芽 } // 開啟藍芽 if (!adapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 設定藍芽可見性,最多300秒 intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); context.startActivity(intent); } // 檢查裝置是否支援藍芽 adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { // 裝置不支援藍芽 } // 開啟藍芽 if (!adapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 設定藍芽可見性,最多300秒 intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); context.startActivity(intent); } 3.獲取已配對的藍芽裝置(android.bluetooth.BluetoothDevice) 首次連線某藍芽裝置需要先配對,一旦配對成功,該裝置的資訊會被儲存,以後連線時無需再配對,所以已配對的裝置不一定是能連線的。 [java] BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> devices = adapter.getBondedDevices(); for(int i=0; i<devices.size(); i++) { BluetoothDevice device = (BluetoothDevice) devices.iterator().next(); System.out.println(device.getName()); } BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> devices = adapter.getBondedDevices(); for(int i=0; i<devices.size(); i++) { BluetoothDevice device = (BluetoothDevice) devices.iterator().next(); System.out.println(device.getName()); } 4.搜尋周圍的藍芽裝置 介面卡搜尋藍芽裝置後將結果以廣播形式傳出去,所以需要自定義一個繼承廣播的類,在onReceive方法中獲得並處理藍芽裝置的搜尋結果。 [java] // 設定廣播資訊過濾 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothDevice.ACTION_FOUND); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // 註冊廣播接收器,接收並處理搜尋結果 context.registerReceiver(receiver, intentFilter); // 尋找藍芽裝置,android會將查詢到的裝置以廣播形式發出去 adapter.startDiscovery(); // 設定廣播資訊過濾 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothDevice.ACTION_FOUND); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // 註冊廣播接收器,接收並處理搜尋結果 context.registerReceiver(receiver, intentFilter); // 尋找藍芽裝置,android會將查詢到的裝置以廣播形式發出去 adapter.startDiscovery(); 自定義廣播類 [java] private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getName()); } } } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getName()); } } } 5.藍芽裝置的配對和狀態監視 [java] private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 獲取查詢到的藍芽裝置 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getName()); // 如果查詢到的裝置符合要連線的裝置,處理 if (device.getName().equalsIgnoreCase(name)) { // 搜尋藍芽裝置的過程佔用資源比較多,一旦找到需要連線的裝置後需要及時關閉搜尋 adapter.cancelDiscovery(); // 獲取藍芽裝置的連線狀態 connectState = device.getBondState(); switch (connectState) { // 未配對 case BluetoothDevice.BOND_NONE: // 配對 try { Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); createBondMethod.invoke(device); } catch (Exception e) { e.printStackTrace(); } break; // 已配對 case BluetoothDevice.BOND_BONDED: try { // 連線 connect(device); } catch (IOException e) { e.printStackTrace(); } break; } } } else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { // 狀態改變的廣播 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getName().equalsIgnoreCase(name)) { connectState = device.getBondState(); switch (connectState) { case BluetoothDevice.BOND_NONE: break; case BluetoothDevice.BOND_BONDING: break; case BluetoothDevice.BOND_BONDED: try { // 連線 connect(device); } catch (IOException e) { e.printStackTrace(); } break; } } } } } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 獲取查詢到的藍芽裝置 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getName()); // 如果查詢到的裝置符合要連線的裝置,處理 if (device.getName().equalsIgnoreCase(name)) { // 搜尋藍芽裝置的過程佔用資源比較多,一旦找到需要連線的裝置後需要及時關閉搜尋 adapter.cancelDiscovery(); // 獲取藍芽裝置的連線狀態 connectState = device.getBondState(); switch (connectState) { // 未配對 case BluetoothDevice.BOND_NONE: // 配對 try { Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); createBondMethod.invoke(device); } catch (Exception e) { e.printStackTrace(); } break; // 已配對 case BluetoothDevice.BOND_BONDED: try { // 連線 connect(device); } catch (IOException e) { e.printStackTrace(); } break; } } } else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { // 狀態改變的廣播 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getName().equalsIgnoreCase(name)) { connectState = device.getBondState(); switch (connectState) { case BluetoothDevice.BOND_NONE: break; case BluetoothDevice.BOND_BONDING: break; case BluetoothDevice.BOND_BONDED: try { // 連線 connect(device); } catch (IOException e) { e.printStackTrace(); } break; } } } } } 6.藍芽裝置的連線 [java] private void connect(BluetoothDevice device) throws IOException { // 固定的UUID final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; UUID uuid = UUID.fromString(SPP_UUID); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); } private void connect(BluetoothDevice device) throws IOException { // 固定的UUID final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; UUID uuid = UUID.fromString(SPP_UUID); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); } 本篇文章來源於 Linux公社網站(www.linuxidc.com) 原文連結:http://www.linuxidc.com/Linux/2011-12/48374.htm 1.BluetoothAdapter 顧名思義,藍芽介面卡,直到我們建立bluetoothSocket連線之前,都要不斷操作它 BluetoothAdapter裡的方法很多,常用的有以下幾個: cancelDiscovery() 根據字面意思,是取消發現,也就是說當我們正在搜尋裝置的時候呼叫這個方法將不再繼續搜尋 disable()關閉藍芽 enable()開啟藍芽,這個方法開啟藍芽不會彈出提示,更多的時候我們需要問下使用者是否開啟,一下這兩行程式碼同樣是開啟藍芽,不過會提示使用者: Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enabler,reCode);//同startActivity(enabler); getAddress()獲取本地藍芽地址 getDefaultAdapter()獲取預設BluetoothAdapter,實際上,也只有這一種方法獲取BluetoothAdapter getName()獲取本地藍芽名稱 getRemoteDevice(String address)根據藍芽地址獲取遠端藍芽裝置 getState()獲取本地藍芽介面卡當前狀態(感覺可能除錯的時候更需要) isDiscovering()判斷當前是否正在查詢裝置,是返回true isEnabled()判斷藍芽是否開啟,已開啟返回true,否則,返回false listenUsingRfcommWithServiceRecord(String name,UUID uuid)根據名稱,UUID建立並返回BluetoothServerSocket,這是建立BluetoothSocket伺服器端的第一步 startDiscovery()開始搜尋,這是搜尋的第一步 2.BluetoothDevice看名字就知道,這個類描述了一個藍芽裝置 createRfcommSocketToServiceRecord(UUIDuuid)根據UUID建立並返回一個BluetoothSocket 這個方法也是我們獲取BluetoothDevice的目的——建立BluetoothSocket 這個類其他的方法,如getAddress(),getName(),同BluetoothAdapter 3.BluetoothServerSocket如果去除了Bluetooth相信大家一定再熟悉不過了,既然是Socket,方法就應該都差不多, 這個類一種只有三個方法 兩個過載的accept(),accept(inttimeout)兩者的區別在於後面的方法指定了過時時間,需要注意的是,執行這兩個方法的時候,直到接收到了客戶端的請求(或是過期之後),都會阻塞執行緒,應該放在新執行緒裡執行! 還有一點需要注意的是,這兩個方法都返回一個BluetoothSocket,最後的連線也是伺服器端與客戶端的兩個BluetoothSocket的連線 close()這個就不用說了吧,翻譯一下——關閉! 4.BluetoothSocket,跟BluetoothServerSocket相對,是客戶端 一共5個方法,不出意外,都會用到 close(),關閉 connect()連線 getInptuStream()獲取輸入流 getOutputStream()獲取輸出流 getRemoteDevice()獲取遠端裝置,這裡指的是獲取bluetoothSocket指定連線的那個遠端藍芽裝置