This article describes a simple Bluetooth program implemented by Android. Share it for your reference, as follows:
I will introduce the Android Bluetooth program in this post. This program is a remote control that turns the phone into a computer PPT playback: use the volume plus and volume down keys to control the switching of the PPT page.
Remote Control Server
First, we need to write a server side of the remote control (a computer that supports Bluetooth) to receive signals from the mobile phone. In order to implement this server side, I used a Java library called Bluecove (specially used to serve Bluetooth!).
Here is my RemoteBluetoothServer class:
public class RemoteBluetoothServer{ public static void main(String[] args) { Thread waitThread = new Thread(new WaitThread()); (); } }
A thread is created in the main method to connect to the client and process the signal.
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 = (); (); UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb" String url = "btspp://localhost:" + () + ";name=RemoteBluetooth"; notifier = (StreamConnectionNotifier)(url); } catch (Exception e) { (); return; } // waiting for connection while(true) { try { ("waiting for connection..."); connection = (); Thread processThread = new Thread(new ProcessConnectionThread(connection)); (); } catch (Exception e) { (); return; } } } }
In waitForConnection(), first set the server to discoverable, and create a UUID for this program (for communication with the client); then wait for the connection request from the client. When it receives an initial connection request, a ProcessConnectionThread is created to process the commands from the client. Here is the code for 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 = (); ("waiting for input"); while (true) { int command = (); if (command == EXIT_CMD) { ("finish process"); break; } processCommand(command); } } catch (Exception e) { (); } } /** * 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: (KeyEvent.VK_RIGHT); ("Right"); break; case KEY_LEFT: (KeyEvent.VK_LEFT); ("Left"); break; } } catch (Exception e) { (); } } }
The ProcessConnectionThread class is mainly used to receive and process commands sent by the client. There are only two commands to be processed: KEY_RIGHT and KEY_LEFT. I use it to generate keyboard events on the computer.
The above is what the server needs to do.
Remote Control Client
The client here actually refers to Android phones. In the process of developing mobile phone code, I referred to the code of the Bluetooth Chat program in the Android Dev Guide, which can be found in the SDK sample code.
To connect the client to the server, you must allow the phone to scan to the computer. The task of the DeviceListActivity class is to scan and connect to the server. The BluetoothCommandService class is responsible for passing commands to the server. These two classes are similar to what is in Bluetooth Chat, except that AcceptThread in BluetoothCommandService in Bluetooth Chat, because the client does not need to accept connection requests. ConnectThread is used to initialize the connection to the server, and ConnectedThread is used to send commands.
RemoteBluetooth is the main activity of the client, the main code is as follows:
protected void onStart() { (); // If BT is not on, request that it be enabled. // setupCommand() will then be called during onActivityResult if (!()) { 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() is used to check if the Bluetooth on the phone is turned on, and if it is not turned on, create an Intent to turn on Bluetooth. setupCommand() is used to send commands to the server when the volume plus or volume down key is pressed. The onKeyDown event is used:
public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { (BluetoothCommandService.VOL_UP); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){ (BluetoothCommandService.VOL_DOWN); return true; } return (keyCode, event); }
In addition, you need to add a code to enable Bluetooth permissions.
<uses-permission android:name=".BLUETOOTH_ADMIN" /> <uses-permission android:name="" />
The above is the client's code.
After installing the two programs on the computer and mobile phone, you can use the phone as a PPT remote control!
PS: For details, please refer to the online tools of this site:
Android Manifest function and permission description:
http://tools./table/AndroidManifest
For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android View View Tips Summary》、《Android programming activity operation skills summary》、《Summary of Android's SQLite database skills》、《Summary of Android data skills for operating json format》、《Android database operation skills summary》、《Android file operation skills summary》、《A summary of SD card operation methods for Android programming and development》、《Android resource operation skills summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.