Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序示例
本文實(shí)例講述了Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序。分享給大家供大家參考,具體如下:
我將在這篇文章中介紹了的Android藍(lán)牙程序。這個(gè)程序就是將實(shí)現(xiàn)把手機(jī)變做電腦PPT播放的遙控器:用音量加和音量減鍵來(lái)控制PPT頁(yè)面的切換。
遙控器服務(wù)器端
首先,我們需要編寫(xiě)一個(gè)遙控器的服務(wù)器端(支持藍(lán)牙的電腦)來(lái)接收手機(jī)端發(fā)出的信號(hào)。為了實(shí)現(xiàn)這個(gè)服務(wù)器端,我用到了一個(gè)叫做Bluecove(專(zhuān)門(mén)用來(lái)為藍(lán)牙服務(wù)的?。┑腏ava庫(kù)。
以下是我的RemoteBluetoothServer類(lèi):
public class RemoteBluetoothServer{
public static void main(String[] args) {
Thread waitThread = new Thread(new WaitThread());
waitThread.start();
}
}
在主方法中創(chuàng)建了一個(gè)線程,用于連接客戶端,并處理信號(hào)。
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()中,首先將服務(wù)器設(shè)為可發(fā)現(xiàn)的,并為這個(gè)程序創(chuàng)建了UUID(用于同客戶端通信);然后就等待來(lái)自客戶端的連接請(qǐng)求。當(dāng)它收到一個(gè)初始的連接請(qǐng)求時(shí),將創(chuàng)建一個(gè)ProcessConnectionThread來(lái)處理來(lái)自客戶端的命令。以下是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類(lèi)主要用于接收并處理客戶端發(fā)送的命令。需要處理的命令只有兩個(gè):KEY_RIGHT和KEY_LEFT。我用java.awt.Robot來(lái)生成電腦端的鍵盤(pán)事件。
以上就是服務(wù)器端所需要做的工作。
遙控器客戶端
這里的客戶端指的其實(shí)就是Android手機(jī)。在開(kāi)發(fā)手機(jī)端代碼的過(guò)程中,我參考了 Android Dev Guide中Bluetooth Chat這個(gè)程序的代碼,這個(gè)程序在SDK的示例代碼中可以找到。
要將客戶端連接服務(wù)器端,那么必須讓手機(jī)可以掃描到電腦,DeviceListActivity 類(lèi)的工作就是掃描并連接服務(wù)器。BluetoothCommandService類(lèi)負(fù)責(zé)將命令傳至服務(wù)器端。這兩個(gè)類(lèi)與Bluetooth Chat中的內(nèi)容相似,只是刪除了Bluetooth Chat中的BluetoothCommandService中的AcceptThread ,因?yàn)榭蛻舳瞬恍枰邮苓B接請(qǐng)求。ConnectThread用于初始化與服務(wù)器的連接,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ī)上的藍(lán)牙是否已經(jīng)打開(kāi),如果沒(méi)有打開(kāi)則創(chuàng)建一個(gè)Intent來(lái)打開(kāi)藍(lán)牙。setupCommand()用于在按下音量加或音量減鍵時(shí)向服務(wù)器發(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加入打開(kāi)藍(lán)牙的權(quán)限的代碼。
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" />
以上就是客戶端的代碼。
將兩個(gè)程序分別在電腦和手機(jī)上安裝后,即可實(shí)現(xiàn)用手機(jī)當(dāng)作一個(gè)PPT遙控器了!
PS:關(guān)于AndroidManifest.xml詳細(xì)內(nèi)容可參考本站在線工具:
Android Manifest功能與權(quán)限描述大全:
http://tools.jb51.net/table/AndroidManifest
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android操作SQLite數(shù)據(jù)庫(kù)技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫(kù)操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android編程開(kāi)發(fā)之SD卡操作方法匯總》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
相關(guān)文章
Flutter實(shí)現(xiàn)手勢(shì)識(shí)別功能詳解方法
在Flutter中使用GestureDetector可以來(lái)完成對(duì)手勢(shì)的識(shí)別,包括長(zhǎng)按、滑動(dòng)、雙擊等手勢(shì),這篇文章主要介紹了Flutter實(shí)現(xiàn)手勢(shì)識(shí)別功能2022-11-11
Android LayoutInflater.inflate源碼分析
這篇文章主要介紹了Android LayoutInflater.inflate源碼分析的相關(guān)資料,需要的朋友可以參考下2016-12-12
Android DynamicGrid實(shí)現(xiàn)拖曳交換位置功能
這篇文章主要為大家詳細(xì)介紹了Android DynamicGrid實(shí)現(xiàn)拖曳交換位置功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
Android仿微信、qq點(diǎn)擊右上角加號(hào)彈出操作框
這篇文章主要為大家詳細(xì)介紹了Android仿微信、qq點(diǎn)擊右上角加號(hào)彈出操作框,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
Android init.rc文件詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了Android init.rc文件詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-01-01
Android實(shí)現(xiàn)滑動(dòng)側(cè)邊欄
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)滑動(dòng)側(cè)邊欄效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12

