Android Bluetooth technology using the process of detailed _android

Source: Internet
Author: User
Tags uuid

In the previous article to introduce the Android Bluetooth Bluetooth technology experience related content, interested friends can click to learn more details.

One: The communication between Bluetooth devices mainly includes four steps

Setting up a Bluetooth device
Look for possible or matching devices within a local area network
Connecting devices
Data transfer between devices

Two: the concrete programming realizes

1. Start Bluetooth function

The Bluetooth adapter bluetoothadapter is first obtained by calling the static method Getdefaultadapter (), and cannot continue if returned to null. For example:

Bluetoothadapter mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();
if (Mbluetoothadapter = = null) {
//Device does not support Bluetooth
}

Second, call IsEnabled () to query the status of the current Bluetooth device, if returned to false, the Bluetooth device is not turned on, then you need to encapsulate a action_request_enable request to intent inside, Call the Startactivityforresult () method to enable the Bluetooth device, for example:

if (!mbluetoothadapter.isenabled ()) {
Intent enablebtintent = new Intent (bluetoothadapter.action_request_enable) ;
Startactivityforresult (Enablebtintent, REQUEST_ENABLE_BT);
}

2. Find Equipment

Using the methods in the Bluetoothadapter class, you can look for remote devices (about 10 meters or less) or find other devices that have been matched (or bound) on your phone. Of course you need to make sure that the other Bluetooth device is turned on or that the "found enabled" feature (the other device can be found is a prerequisite for you to initiate the connection). If the device can be found, feedback back some of the device information, such as the name, MAC address, etc., using this information, your device can choose to initialize a connection to each other.

If you are connected to the device for the first time, a matching request is automatically displayed to the user. When the device is paired, some of his basic information (mainly name and Mac) is saved and can be read using the Bluetooth API. You can initiate a connection request to a remote Bluetooth device using a known MAC address.
The difference between a good device and a device on a connection: the match only means that the other device has found your presence and has a common identification code and can connect. Connection: Indicates that the current device shares a RFCOMM channel and can exchange data between them. That is to say, the Bluetooth device must have been paired before establishing the Rfcomm channel.

3. Query the right equipment

Before establishing a connection you must first query the paired set of Bluetooth devices to select a device for communication, for example, you can query all paired Bluetooth devices and use an array adapter to print them out:

Set<bluetoothdevice> paireddevices =mbluetoothadapter.getbondeddevices ();
If there are paired devices
if (paireddevices.size () > 0) {//loop through paired devices for
(Bluetooth Device device:paireddevices) {
//ADD the name and address to a ListView
marrayadapt Er.add (Device.getname () + "\ n" + device.getaddress ());
}

It is sufficient to establish a Bluetooth connection that requires only a MAC address.

4. Scanning equipment

Scanning devices, you only need to call the StartDiscovery () method, the process of scanning is approximately 12 seconds, the application for Action_found action needs to register a broadcastreceiver to accept the device scan the information. For each device, the system broadcasts the Action_found action.

Register a broadcast receiver with Action_found for action
private final Broadcastreceiver mreceiver = new Broadcastreceiver () {
public void OnReceive (Context context, Intent Intent) {
String action = intent.getaction ();
Discovery Device
if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
//Get Bluetooth device from intent
bluetoothdevice device = Intent.getparcelableextra (bluetoothdevice.extra_device);
Add name and address to the device adapter
Marrayadapter.add (device.getname () + "\ n" + device.getaddress ());}}
;
Registered broadcast Receiver
Intentfilter filter = new Intentfilter (bluetoothdevice.action_found);
Registerreceiver (mreceiver, filter); Remember to unregister the broadcast receiver when OnDestroy

5. Enable to be found

If you want to make your device visible to other devices, encapsulate the action_request_discoverable action in the Intent and invoke the Startactivityforresult (Intent, int) method. It will enable your device to be discovered without leaving your application out of the picture. By default, the enabling time is 120 seconds, and of course you can change the enabling time (up to 300 seconds) by adding the Extra_discoverable_duration field, for example:

Intent discoverableintent = new Intent (bluetoothadapter.action_request_discoverable);
Discoverableintent.putextra (bluetoothadapter.extra_discoverable_duration);
StartActivity (discoverableintent);

After running this section of code, the system will pop up a dialog box to prompt you to start the device so that it can be detected (if your Bluetooth function is not turned on during this process, the system will open it for you), and if you are ready to find a connection to the remote device, you do not need to turn on the device to be found Because this functionality is only needed when your application is server-side.

6. Connecting Equipment

In your application, to establish a connection between two Bluetooth devices, you must implement the client and server-side code (since any device must be either a server-side or a client). An open service to listen, a request to initiate a connection (using the MAC address of the server-side device). When they all have a Bluetooth socket on the same Rfecomm channel, they can assume that they are already connected. The server and the client pass in different ways or their Bluetooth sockets. When a connection is heard, the server gets the Bluetooth socket. When a customer can open a Frcomm channel to the server side, the client acquires the Bluetooth socket.

Note: In this process, if two Bluetooth devices are not paired properly, the Android system notifies the user in the form of a notification or dialog box. Rfcomm connection requests are blocked before the user chooses.

7. Service-Side Connection

When you want to connect two devices, one must serve as a service (by holding an open bluetoothserversocket), in order to listen for foreign connection requests, and when the monitor is heard, provide a connection to the Bluetoothsocket to the client, When the client gets bluetoothsocket from Bluetoothserversocket, it can destroy bluetoothserversocket unless you want to listen for more connection requests.
Basic steps for establishing a service socket and listening for connections:
First, the Bluetoothserversocket object is obtained by calling the Listenusingrfcommwithservicerecord (string, UUID) method, and the parameter String represents the name of the service. The UUID represents an identity with the client connection (a 128-bit format string ID, equivalent to a pin), and the UUID must match to establish the connection.

Second, call the Accept () method to listen for possible connection requests, and when the monitor is heard, return a Bluetooth socket bluetoothsocket on the connection.
Finally, after you hear a connection, you need to call the close () method to turn off the listener. (a point-to-point transmission between common Bluetooth devices)
Note: the Accept () method should not be placed in the main acitvity because it is a blocking call (the program stops there until the connection request is heard). The workaround is to create a new thread to manage. For example:

8. Client-side connections

To initialize a connection to a remote device, you need to first obtain a Bluetoothdevice object that represents the device. To get the Bluetoothsocket and initialize the connection by Bluetoothdevice the object, specify the steps:

Use the method Createrfcommsockettoservicerecord (UUID) in the Bluetoothdevice object to obtain the Bluetoothsocket. A UUID is a matching code. Then, call the Connect () method. If the remote device receives the connection, they will share the Rffcomm channel during the communication and return connect.

Note: the Conncet () method is also a blocking call, which generally creates a separate thread to invoke the method. Connection connect () should not be initiated during device discover, which slows down significantly so that the connection fails. And the data transfer completes only by calling the close () method to shut down the connection, which saves the internal resources of the system.

9. Manage Connections

When the device is connected, each device has its own bluetoothsocket. You can realize the sharing of data between devices.
The input output stream is first obtained by calling the getInputStream () and the Getoutputstream () method.
Then by calling read (byte[]) and write (byte[]). method to read or write data.
Implementation details: For both read and write operations are blocking calls, you need to establish a dedicated thread to manage.

10. Permission settings

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

The above is a small set for everyone to share the Android Bluetooth technology to use the process of detailed explanation, I hope to help.

Related Article

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.