標籤:rate extend 藍芽 ide ever 開啟藍芽 建立串連 pre ret
Android藍芽開發近期做藍芽小車,須要Android端來控制小車的運動。以此文記錄開發過程。
使用HC-06無線藍芽串口透傳模組。對於其它的藍牙裝置本文相同適用。
藍芽開發的流程:
擷取本地藍芽適配器 ——> 開啟藍芽 ——> 搜尋裝置 ——> 串連裝置 ——> 發送資訊
首先為了避免以往我們先寫入藍芽許可權:
<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
要用到的藍芽對象:
private BluetoothAdapter adapter = null;//用於擷取藍芽適配器private BluetoothDevice mBtDevice = null;//用於擷取藍牙裝置private BluetoothSocket mBtSocket = null;//用於建立通訊
擷取藍芽適配器:
adapter = BluetoothAdapter.getDefaultAdapter();
開啟藍芽:
boolean enabled = adapter.enable();if(!enabled){ adapter.enable();}
搜尋裝置:
adapter.startDiscovery();
搜尋到的裝置會以廣播的形式返回,所以我們須要定義一個廣播接收器:
private BroadcastReceiver blueRevever = new BroadcastReceiver(){@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString action = intent.getAction();if(action.equals(BluetoothDevice.ACTION_FOUND)){BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if(device.getBondState()!=BluetoothDevice.BOND_BONDED){//擷取未配對的裝置名稱和MAC地址//依據搜尋到的藍牙裝置的MAC地址,得到該裝置mBtDevice = adapter.getRemoteDevice(device.getAddress()); //假設裝置名稱是指定的裝置則給出提示if(device.getName().equals("HC-06")){Toast.makeText(MainActivity.this,device.getName(),Toast.LENGTH_LONG).show();}}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {Toast.makeText(MainActivity.this,"檢測完成",Toast.LENGTH_LONG).show();}}}};
廣播返回不同裝置及其所處的狀態。getAction()方法用於擷取狀態,BOND_BONDED表示是已經配對的狀態。(注意配對和串連是兩個全然不同的概念,配對成功並非串連成功,只配對成功不可以發送資訊)
當然是用廣播機制要注意注冊廣播:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(blueRevever, filter); filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(blueRevever, filter);
串連裝置:
由於堵塞串連會堵塞線程,所以我們須要重開一個新的線程用於建立串連:
private class clientThread extends Thread{ public void run(){ try { //取消搜尋裝置的動作。否則接下來的裝置串連會失敗 adapter.cancelDiscovery(); //依據device擷取socket mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); //串連socket mBtSocket.connect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(MainActivity.this,"串連失敗!。。!!
!
!!!",Toast.LENGTH_LONG).show(); } } }
此處的UUID用於串連HC-06是可行的。其它的裝置未測試
想使用時僅僅需建立一個clientThread對象,然後運行其run()方法就可以,例如以下:
//建立串連的進程Thread mBtClientConnectThread = new clientThread(); //開啟進程mBtClientConnectThread.start();
發送資訊:
public void sendMessageHandle(String msg) { if (mBtSocket == null) { Toast.makeText(MainActivity.this,"沒有串連!。",Toast.LENGTH_LONG).show(); return; } try { OutputStream os = mBtSocket.getOutputStream(); os.write(msg.getBytes()); //發送出去的值為:msg Toast.makeText(MainActivity.this,"發送成功!!
",Toast.LENGTH_LONG).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(MainActivity.this,"發送失敗!
!!
。!!
!!!
",Toast.LENGTH_LONG).show(); } }
此處的UUID用於串連HC-06是可行的,其它的裝置未測試
Android藍芽開發