Android實現(xiàn)的簡單藍牙程序示例
本文實例講述了Android實現(xiàn)的簡單藍牙程序。分享給大家供大家參考,具體如下:
我將在這篇文章中介紹了的Android藍牙程序。這個程序就是將實現(xiàn)把手機變做電腦PPT播放的遙控器:用音量加和音量減鍵來控制PPT頁面的切換。
遙控器服務器端
首先,我們需要編寫一個遙控器的服務器端(支持藍牙的電腦)來接收手機端發(fā)出的信號。為了實現(xiàn)這個服務器端,我用到了一個叫做Bluecove(專門用來為藍牙服務的?。┑腏ava庫。
以下是我的RemoteBluetoothServer類:
public class RemoteBluetoothServer{ public static void main(String[] args) { Thread waitThread = new Thread(new WaitThread()); waitThread.start(); } }
在主方法中創(chuàng)建了一個線程,用于連接客戶端,并處理信號。
public class WaitThread implements Runnable{ /** Constructor */ public WaitThread() { } @Override public void run() { waitForConnection(); } /** Waiting for connection from devices */ private void waitForConnection() { // retrieve the local Bluetooth device object LocalDevice local = null; StreamConnectionNotifier notifier; StreamConnection connection = null; // setup the server to listen for connection try { local = LocalDevice.getLocalDevice(); local.setDiscoverable(DiscoveryAgent.GIAC); UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb" String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth"; notifier = (StreamConnectionNotifier)Connector.open(url); } catch (Exception e) { e.printStackTrace(); return; } // waiting for connection while(true) { try { System.out.println("waiting for connection..."); connection = notifier.acceptAndOpen(); Thread processThread = new Thread(new ProcessConnectionThread(connection)); processThread.start(); } catch (Exception e) { e.printStackTrace(); return; } } } }
在waitForConnection()中,首先將服務器設為可發(fā)現(xiàn)的,并為這個程序創(chuàng)建了UUID(用于同客戶端通信);然后就等待來自客戶端的連接請求。當它收到一個初始的連接請求時,將創(chuàng)建一個ProcessConnectionThread來處理來自客戶端的命令。以下是ProcessConnectionThread的代碼:
public class ProcessConnectionThread implements Runnable{ private StreamConnection mConnection; // Constant that indicate command from devices private static final int EXIT_CMD = -1; private static final int KEY_RIGHT = 1; private static final int KEY_LEFT = 2; public ProcessConnectionThread(StreamConnection connection) { mConnection = connection; } @Override public void run() { try { // prepare to receive data InputStream inputStream = mConnection.openInputStream(); System.out.println("waiting for input"); while (true) { int command = inputStream.read(); if (command == EXIT_CMD) { System.out.println("finish process"); break; } processCommand(command); } } catch (Exception e) { e.printStackTrace(); } } /** * Process the command from client * @param command the command code */ private void processCommand(int command) { try { Robot robot = new Robot(); switch (command) { case KEY_RIGHT: robot.keyPress(KeyEvent.VK_RIGHT); System.out.println("Right"); break; case KEY_LEFT: robot.keyPress(KeyEvent.VK_LEFT); System.out.println("Left"); break; } } catch (Exception e) { e.printStackTrace(); } } }
ProcessConnectionThread類主要用于接收并處理客戶端發(fā)送的命令。需要處理的命令只有兩個:KEY_RIGHT和KEY_LEFT。我用java.awt.Robot來生成電腦端的鍵盤事件。
以上就是服務器端所需要做的工作。
遙控器客戶端
這里的客戶端指的其實就是Android手機。在開發(fā)手機端代碼的過程中,我參考了 Android Dev Guide中Bluetooth Chat這個程序的代碼,這個程序在SDK的示例代碼中可以找到。
要將客戶端連接服務器端,那么必須讓手機可以掃描到電腦,DeviceListActivity 類的工作就是掃描并連接服務器。BluetoothCommandService類負責將命令傳至服務器端。這兩個類與Bluetooth Chat中的內(nèi)容相似,只是刪除了Bluetooth Chat中的BluetoothCommandService中的AcceptThread ,因為客戶端不需要接受連接請求。ConnectThread用于初始化與服務器的連接,ConnectedThread 用于發(fā)送命令。
RemoteBluetooth 是客戶端的主activity,其中主要代碼如下:
protected void onStart() { super.onStart(); // If BT is not on, request that it be enabled. // setupCommand() will then be called during onActivityResult if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } // otherwise set up the command service else { if (mCommandService==null) setupCommand(); } } private void setupCommand() { // Initialize the BluetoothChatService to perform bluetooth connections mCommandService = new BluetoothCommandService(this, mHandler); }
onStart()用于檢查手機上的藍牙是否已經(jīng)打開,如果沒有打開則創(chuàng)建一個Intent來打開藍牙。setupCommand()用于在按下音量加或音量減鍵時向服務器發(fā)送命令。其中用到了onKeyDown事件:
public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { mCommandService.write(BluetoothCommandService.VOL_UP); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){ mCommandService.write(BluetoothCommandService.VOL_DOWN); return true; } return super.onKeyDown(keyCode, event); }
此外,還需要在AndroidManifest.xml加入打開藍牙的權限的代碼。
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" />
以上就是客戶端的代碼。
將兩個程序分別在電腦和手機上安裝后,即可實現(xiàn)用手機當作一個PPT遙控器了!
PS:關于AndroidManifest.xml詳細內(nèi)容可參考本站在線工具:
Android Manifest功能與權限描述大全:
http://tools.jb51.net/table/AndroidManifest
更多關于Android相關內(nèi)容感興趣的讀者可查看本站專題:《Android開發(fā)入門與進階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android操作SQLite數(shù)據(jù)庫技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android編程開發(fā)之SD卡操作方法匯總》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設計有所幫助。
相關文章
Android LayoutInflater.inflate源碼分析
這篇文章主要介紹了Android LayoutInflater.inflate源碼分析的相關資料,需要的朋友可以參考下2016-12-12Android DynamicGrid實現(xiàn)拖曳交換位置功能
這篇文章主要為大家詳細介紹了Android DynamicGrid實現(xiàn)拖曳交換位置功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06