Android implementation of the simple Bluetooth program sample _android

Source: Internet
Author: User
Tags sqlite database uuid

This example describes the simple Bluetooth program implemented by Android. Share to everyone for your reference, specific as follows:

I will introduce the Android Bluetooth program in this article. This program is to realize the mobile phone as a computer PPT playback of the remote control: the volume Plus and volume reduction keys in order to manage the PPT page switch.

Remote control server Side

First, we need to write a remote control server (Bluetooth-enabled computer) to receive the signal from the phone. In order to implement this server side, I used a called bluecove (specially used for Bluetooth service!) ) Java Library.

Here's my Remotebluetoothserver class:

public class remotebluetoothserver{public
  static void Main (string[] args) {
    thread waitthread = new Thread (New Wa Itthread ());
    Waitthread.start ();
  }


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 R
  Un () {waitforconnection (); }/** waiting for connection from devices */private void waitforconnection () {//Retrieve the local Bluetooth de
    Vice 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=remotebluetoo
      TH ";
    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

 }
    }
  }
}

in Waitforconnection (), the server is first set to be discovered and a UUID is created for the program to communicate with the client, and then the connection request from the client is awaited. When it receives an initial connection request, a processconnectionthread is created to process the commands from the client. The following 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 = 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 {RobotRobot = 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 ();

 }
  }
}

The Processconnectionthread class is primarily used to receive and process commands sent by clients. There are only two commands to handle: Key_right and Key_left. I use Java.awt.Robot to generate keyboard events on the computer side.

The above is the work that the server side needs to do.

Remote Control Client

The client here is actually the Android phone. In the process of developing the phone-side code, I consulted the code of the Bluetooth chat program in the Android Dev Guide, which was found in the SDK sample code.

To connect the client to the server, you must have the phone scan to the computer, and the Devicelistactivity class is to scan and connect to the server. The Bluetoothcommandservice class is responsible for passing commands to the server side. These two classes are similar to the contents of the Bluetooth chat, except that the Acceptthread in the bluetoothcommandservice in the Bluetooth chat is removed because the client does not need to accept the connection request. 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, where the main code is as follows:

protected void OnStart () {
  super.onstart ();
  If BT is isn't on, request this it is enabled.
    SetupCommand () would 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 () is used to check whether Bluetooth on the phone is turned on, and if not, create a intent to turn on Bluetooth. SetupCommand () is used to send commands to the server when volume plus or volume subtraction is pressed. Where the onkeydown event was used:

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);
}

In addition, you will need to add the code that opens the Bluetooth permission in Androidmanifest.xml.

<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/>
  <uses-permission android:name = "Android.permission.BLUETOOTH"/>

The above is the client code.

Two programs are installed on the computer and mobile phone, you can realize using a mobile phone as a PPT remote!

PS: About Androidmanifest.xml details can refer to the site online tools:

Android manifest Features and Permissions description Encyclopedia:

Http://tools.jb51.net/table/AndroidManifest

More interested readers of Android-related content can view the site: Android Development Primer and Advanced tutorials, the Android View View tips Summary, the activity tips summary of Android programming, Android Operation SQLite Database skills Summary, "Android operation JSON format Data Skills summary", "Android Database Operation skills Summary", "Android File Operation skills Summary", "Android programming development of SD card operation method Summary", " Android Resource Operation tips Summary and the "Android Controls usage Summary"

I hope this article will help you with the Android program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.