Detailed android--Bluetooth technology brings you to achieve the data transmission between terminals _android

Source: Internet
Author: User
Tags thread class uuid

Bluetooth technology in the smart hardware has a lot to play, today I will share with you the Bluetooth in the Android system of the use of techniques, and to achieve the two data transmission between terminals.

Bluetooth is a short-range wireless communication technology standard, Bluetooth protocol is divided into 4 layers, namely core protocol layer, cable replacement protocol layer, telephone control protocol layer and other protocol layer adopted.

The most important of these 4 agreements is the core agreement. The core protocols of Bluetooth include baseband, link management, Logic link control and adaptation protocol four parts. where link management (LMP) is responsible for the establishment of the connection between Bluetooth components. The logic link control and adaptation Protocol (L2CAP) is located on the baseband protocol layer and belongs to the data link layer, and is an adaptive protocol for shielding baseband protocol for high level transmission and Application layer protocol.

1. Turn Bluetooth on and off

The first method is relatively straightforward, calling the system dialog directly to start Bluetooth:

Add the required permissions to the Androidmanifest file, and the high version does not require dynamic authorization:

<uses-permission android:name= "Android.permission.BLUETOOTH"/>
Startactivityforresult (New Intent (bluetoothadapter.action_request_enable), 1);

If you do not want the user to see this dialog box, then we can also choose the second method to open Bluetooth silently.

The second method, silently open, does not have a dialog box for method one:

To add the required permissions in the Androidmanifest file:

<!--fit Android6.0-->
<uses-permission android:name= "Android.permission.BLUETOOTH"/>
< Uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name= " Android.permission.ACCESS_FINE_LOCATION "/> 
<uses-permission android:name=" android.permission.ACCESS_ Coarse_location "/> 
<uses-feature
  android:name=" Android.hardware.bluetooth_le "
  android: Required= "true"/>

Because Bluetooth requires the right to include dangerous Permissions, we need to perform dynamic authorization processing in Java code:

private static final int request_bluetooth_permission=10;

private void Requestbluetoothpermission () {
  //Judge system version
  if (Build.VERSION.SDK_INT >=) {
    // Detects whether the current app has a permission
    int checkcallphonepermission = Contextcompat.checkselfpermission (This, 
        Manifest.permission.ACCESS_COARSE_LOCATION);
    Determine if the permission has been authorized if
    (checkcallphonepermission!= packagemanager.permission_granted) {
      //To determine if it is necessary to explain to the user, Why do you want to request this permission
      if (Activitycompat.shouldshowrequestpermissionrationale (this, 
          Manifest.permission.ACCESS_ coarse_location)
        Toast.maketext (This, "Need Bluetooth permission.", 
            Toast.length_short). Show ();
      Activitycompat.requestpermissions (this, new string[]
          {manifest.permission.access_coarse_location},request_ bluetooth_permission);
      return;
    } else{
    }
  } else {
  }
}

Next we can turn on the Bluetooth silently:

Bluetoothadapter mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();
Mbluetoothadapter.enable (); Open
//mbluetoothadapter.disable ();//Close

Now let's take a look at how to search for Bluetooth devices through code.

2. Search for Bluetooth devices by code

Search is divided into active search and passive search.

We started the active search:

(1) Create Bluetoothadapter objects

TextView tvdevices = (TextView) Findviewbyid (r.id.tv_devices);
Bluetoothadapter mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();

(2) We first get and display the list of Bluetooth devices that have been paired

Get the Bluetooth device that has been paired
set<bluetoothdevice> paireddevices = mbluetoothadapter.getbondeddevices ();
if (paireddevices.size () > 0) {for
  (Bluetoothdevice device:paireddevices) {
    tvdevices.append ( Device.getname () + ":" + device.getaddress ());
  }

(3) Below we define the broadcast receiver

Set Broadcast information Filter
intentfilter filter = new Intentfilter ();
Filter.addaction (Bluetoothdevice.action_found);//each device is searched to send one of the broadcast
filter.addaction ( bluetoothadapter.action_discovery_finished/////////////////When all searches are completed, send the broadcast
filter.setpriority (integer.max_value);//Set Priority
//Register Bluetooth search broadcast receiver, receive and process search results
this.registerreceiver (receiver, filter);

The broadcast receiver for the Bluetooth device is as follows:

/**
 * Definition broadcast receiver
/private final Broadcastreceiver receiver = new Broadcastreceiver () {
  @Override
  public void OnReceive (context context, Intent Intent) {
    String action = intent.getaction ();
    if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
      Bluetoothdevice device = Intent.getparcelableextra ( Bluetoothdevice.extra_device);
      if (Device.getbondstate ()!= bluetoothdevice.bond_bonded) {
        tvdevices.append (device.getname () + ":" + Device.getaddress ());
      }
    else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION)) {
      //searched for finished
    }}
  }
;

(4) We create a button and search when the button is clicked, button click event is as follows:

If you are currently searching, cancel the search for if
(Mbluetoothadapter.isdiscovering ()) {
  mbluetoothadapter.canceldiscovery ();
}
Open Search
mbluetoothadapter.startdiscovery ();

3. Bluetooth UUID

Two Bluetooth devices need to use the same UUID when connecting. But many readers may find that there are many models of mobile phones (possibly non-Android phones) using different programs or using Bluetooth to communicate. On the surface, it is almost impossible to use the same uuid between them.

The format of the UUID is as follows:

Xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

The format of the UUID is divided into 5 paragraphs, where the number of characters in the Middle 3 is the same, both 4, the 1th paragraph is 8 characters, and the last paragraph is 12 characters. So the UUID is actually a 8-4-4-4-12 string.

In fact, the UUID is the same as the TCP port, and there are some default values. For example, a service that simulates Bluetooth as a serial port uses a standard UUID:

00001101-0000-1000-8000-00805f9b34fb

In addition, there are a number of standard UUID, such as the following two standard UUID:

Information Synchronization Service: 00001104-0000-1000-8000-00805F9B34FB

File Transfer service: 00001106-0000-1000-8000-00805F9B34FB

4. Data transmission between Bluetooth terminals

The data transmitted over Bluetooth is similar to the socket. Use sockets and ServerSocket on your network to control the reading and writing of data on the client and server side. Bluetooth communication is also done by client and server sockets. The Bluetooth client socket is Bluetoothsocket, and the Bluetooth service socket is bluetoothserversocket. These two classes are in the Android.bluetooth package.

Both Bluetoothsocket and Bluetoothserversocket require a UUID (globally unique identifier, universally unique Identifier), which is equivalent to the port of the socket. The Bluetooth address is equivalent to the IP of the socket.

We started to simulate the transmission of a Bluetooth data:

First look at the client:

(1) Defining global constant variables

Private ListView lvdevices;
Private Bluetoothadapter Mbluetoothadapter;
Private list<string> bluetoothdevices = new arraylist<string> ();
Private arrayadapter<string> Arrayadapter;
Private final UUID My_uuid = uuid
    . FromString ("abcd1234-ab12-ab12-ab12-abcdef123456");//define a
private Bluetoothsocket Clientsocket;
private Bluetoothdevice device; 
Private OutputStream os;//output stream

(2) Doing initialization in the OnCreate method

Mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();

Lvdevices = (ListView) Findviewbyid (r.id.lv_devices);
Get the Bluetooth device that has been paired
set<bluetoothdevice> paireddevices = mbluetoothadapter.getbondeddevices ();
if (paireddevices.size () > 0) {for
  (Bluetoothdevice device:paireddevices) {
    Bluetoothdevices.add ( Device.getname () + ":" + device.getaddress ());
  }
Arrayadapter = new Arrayadapter<string> (this,
    Android. R.layout.simple_list_item_1, Android. r.id.text1,bluetoothdevices);
Lvdevices.setadapter (arrayadapter);
Lvdevices.setonitemclicklistener (this);//activity implement Onitemclicklistener interface

//Send a broadcast
to one device each time it is searched Intentfilter filter = new Intentfilter (bluetoothdevice.action_found);
This.registerreceiver (receiver, filter);
When all searches are finished, send the broadcast
filter = new Intentfilter (bluetoothadapter.action_discovery_finished);
This.registerreceiver (receiver, filter);

The broadcast receiver for the Bluetooth device is as follows:

/**
 * Definition broadcast receiver
/private final Broadcastreceiver receiver = new Broadcastreceiver () {
  @Override
  public void OnReceive (context context, Intent Intent) {
    String action = intent.getaction ();
    if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
      Bluetoothdevice device = Intent.getparcelableextra ( Bluetoothdevice.extra_device);
      if (Device.getbondstate ()!= bluetoothdevice.bond_bonded) {
        bluetoothdevices.add (device.getname () + ":" + Device.getaddress ());
        Arrayadapter.notifydatasetchanged ();//update Adapter
      }

    } else if (Bluetoothadapter.action_discovery_ Finished.equals (Action)) {
      //searched for finished
    }}
  }
;

(4) We create a button and search when the button is clicked, button click event is as follows:

If you are currently searching, cancel the search for if
(Mbluetoothadapter.isdiscovering ()) {
  mbluetoothadapter.canceldiscovery ();
}
Open Search
mbluetoothadapter.startdiscovery ();

(5) Next we set up the list of click events:

@Override public
void Onitemclick (adapterview<?> parent, view view, int position, long id) {
  String s = Arra Yadapter.getitem (position);
  String address = s.substring (S.indexof (":") + 1). Trim ()//resolution of addresses
  ///Active connection to Bluetooth service-side
  try {
    //To determine whether or not currently searching for
    if ( Mbluetoothadapter.isdiscovering ()) {
      mbluetoothadapter.canceldiscovery ();
    }
    try {
      if (device = null) {
        //Get remote device
        device = Mbluetoothadapter.getremotedevice (address);
      }
      if (Clientsocket = = null) {
        //Create client bluetooth socket
        clientsocket = Device.createrfcommsockettoservicerecord (my_ UUID);
        Start connecting Bluetooth, if there is no pairing, the pop-up dialog prompts us to match
        Clientsocket.connect ();
        Gets the output stream (the client points to the server-side output text)
        OS = Clientsocket.getoutputstream ();
      }
    catch (Exception e) {
    }
    ( OS!= null) {
      //To service-side write information
      os.write ("Bluetooth information is coming". GetBytes ("Utf-8"));
    }
  catch (Exception e) {
  }
}

Next look at the service side:

The service side uses another handset, accepts the above handset to send over through the Bluetooth information and displays.

(1) Define global constant quantity:

Private Bluetoothadapter Mbluetoothadapter;
Private Acceptthread Acceptthread;
Private final uuid My_uuid = uuid
    . FromString ("abcd1234-ab12-ab12-ab12-abcdef123456");//the same UUID private as the client
Final String NAME = "Bluetooth_socket";
Private Bluetoothserversocket ServerSocket;
private Bluetoothsocket socket;
Private InputStream is;//Input stream

(2) Define Service Thread class:

Private Handler Handler = new Handler () {public
  void Handlemessage (msg) {
    Toast.maketext ( Getapplicationcontext (), string.valueof (msg.obj),
        Toast.length_long). Show ();
    Super.handlemessage (msg);
  }
;

Server-side listener thread class
private class Acceptthread extends thread {public
  acceptthread () {
    try {
      ServerSocket = Mbluetoothadapter.listenusingrfcommwithservicerecord (NAME, My_uuid);
    } catch (Exception e) {
    }
  } public
  void Run () {
    try {
      socket = serversocket.accept ();
      is = Socket.getinputstream ();
      while (true) {
        byte[] buffer =new byte[1024];
        int count = is.read (buffer);
        msg = new Message ();
        Msg.obj = new String (buffer, 0, Count, "Utf-8");
        Handler.sendmessage (msg);
      }
    catch (Exception e) {
    }
  }
}

(3) Initialize the thread class in the OnCreate method and open

Mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();
Acceptthread = new Acceptthread ();
Acceptthread.start ();

Let's run the program and look at the effect chart:

Click on the "Search Bluetooth Device" button, you will find another mobile phone's Bluetooth information, we click on the item, the other phone will be the following changes:

Pop-up toast, this time to prove that our Bluetooth data has been transmitted over.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.