How to Use Android Bluetooth (Bluetooth details) and Android bluetooth

Source: Internet
Author: User

How to Use Android Bluetooth (Bluetooth details) and Android bluetooth
I. Communication between bluetooth devices consists of four processes.

Configure a bluetooth device to search for devices that may match in the LAN to connect to data transmission between devices.
Ii. completion of detailed programming 1. Activate Bluetooth

First, call the static method getdefaadapter adapter () to obtain the Bluetooth adapter javasthadapter. If the return value is empty, the execution cannot be continued. For example, Android source code:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth }

Second, call isEnabled () to check the status of the bluetooth device at that time. If it is false, it indicates that the bluetooth device is not open. Next, You Need To encapsulate an ACTION_REQUEST_ENABLE and request it to the intent, call startActivityForResult () to enable a bluetooth device, for example:

if (!mBluetoothAdapter.isEnabled()) {    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}
2. Find a device

Using the thadapter class, you can search for remote devices (less than 10 meters) or other devices that have been matched (or bound) on your mobile phone. Of course, the demand determines that the bluetooth device of the other party is now open, or the "Discovery and enable" function may be available now (the other party's device can be found is a prerequisite for you to suggest convergence ). If the device can be found, some device information of the other party, such as the name and MAC address, will be returned, your device will be able to initialize a connection to the other party.
If you connect to the device for the first time, a matching request will be displayed to the user. When the device is paired, some of its basic information (first, name and MAC) will be retained and can be read using the Bluetooth API. Using a known MAC address, we recommend that you connect to the remote Bluetooth device.
The difference between a matched device and a connected device: a matched device only clarifies that the other device has discovered your presence and has a unique identifier. Connection: It indicates that the device shared an RFCOMM channel and the two devices could exchange data. That is to say, the bluetooth device is now paired before setting up the RFCOMM channel.

3. query matched Devices

Before establishing a connection, you must first query the paired bluetooth device set to select a device for communication. For example, you can query all paired Bluetooth devices, and use an array adapter to print and display it:

SetpairedDevices =mBluetoothAdapter.getBondedDevices(); // If there are paired devicesif (pairedDevices.size() > 0) {    //Loop through paired devices    for (BluetoothDevice device : pairedDevices) {        // Add the name and address to an array adapter to show in a ListView        mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); }}

Setting up a Bluetooth connection only requires a MAC address.

4. Scan Devices

Scan the device. You only need to call the startDiscovery () method. The scanning process continues for about 12 seconds. The application needs to register a BroadcastReceiver for the ACTION_FOUND action to bear the information scanned by the device. The System Broadcasts ACTION_FOUND actions for each device.

// Use ACTION_FOUND to register the broadcast receiver private final BroadcastReceiver mReceiver = new BroadcastReceiver () {public void onReceive (Context context, Intent intent) {String action = intent. getAction (); // if (descrithdevice. ACTION_FOUND.equals (action) {// retrieve the bluetooth device from Intent. Then thdevice device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE); // Add the name and address to the mArrayAdapter of the device adapter. add (device. getName () + "\ n" + device. getAddress () ;}}; // register the broadcast receiver IntentFilter filter = new IntentFilter (descrithdevice. ACTION_FOUND); registerReceiver (mReceiver, filter); // remember to publish a broadcast receiver when onDestroy
5. enable Discovery

If you want your device to be discovered by another device, encapsulate the ACTION_REQUEST_DISCOVERABLE action in the intent and call the startActivityForResult (Intent, int) method. It will enable your device to be discovered without exiting your application. By default, the enabling time is 120 seconds. Of course, you can change the enabling time by adding the EXTRA_DISCOVERABLE_DURATION field (up to 300 seconds). For example:

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); 

In the future, the system will pop up a dialog box prompting you to launch a device to enable Discovery (in this process, if your Bluetooth function is not open, the system will open it for you ), in addition, if you want to discover a connection to the remote device, you do not need to open the device discovery function, because this function is only required when your application is used as the server end.

6. Connecting Devices

In applications, to establish a connection between two bluetooth devices, it is necessary to end the client and the server code (because any device must be able to act as a service or client ). An open service listener, a suggestion for connecting requests (using the MAC address of the server device ). When they all have a Bluetooth socket on the same RFECOMM channel, they can think that they are now connected. The service end and the client go through different methods or other users' Bluetooth sockets. When a listener is connected, the service end obtains the Bluetooth socket. When the customer opens an FRCOMM channel for the server end, the client obtains the Bluetooth socket.
Note: In this process, if two bluetooth devices are not paired, the android system will notify the user through a notification or dialog box. RFCOMM connection request will be blocked before the user chooses.

7. Service end connection

When you want to connect two devices, it is necessary to act as a service end (after holding an opened javasthserversocket) to listen for external connection requests, when listening to the future to provide a connection on the thsocket to the client, when the client gets the thsocket from the thserversocket, it will be able to destroy the thserversocket in the future, unless you want to listen to more connection requests.
Establish the basic process of service socket and listener connection:
First, call the listenUsingRfcommWithServiceRecord (String, UUID) method to obtain the objective of ipvthserversocket. The parameter String represents the title of this service, UUID represents an identifier (the string ID of the 128-bit pattern, equivalent to the PIN code) connected to the client. It is necessary for the UUID to match the two sides to establish a connection.
Next, call the accept () method to listen to the connection request that may come. When the listener arrives in the future, a connected Bluetooth socket javasthsocket will be returned.
Finally, in the future, you need to call the close () method to close the listener. (Usually point-to-point transmission between bluetooth devices)
Note: The accept () method should not be placed in the master acit because it is a blocking call (the program has always been there before listening to the connection request ). The solution is to create a new thread. For example:

8. Client Connection

To initialize a connection with a remote device, you need to first obtain a thdevice target that represents the device. The thsocket is obtained through the thdevice target and the connection is initialized. Detailed process:
Use the createRfcommSocketToServiceRecord (UUID) method in the ipvthdevice target to obtain the ipvthsocket. UUID is the matching code. Then, call the connect () method. If the remote device receives the connection, they will share the RFFCOMM channel in the communication process, and connect back.
Note: The conncet () method is also a blocking call. It is usually called by setting up an independent thread. Connect to connect () should not be recommended in the discover process of the device, which will significantly slow down so that the connection fails. When data transmission is complete, you only need to call the close () method to close the connection, which can save internal resources of the system.

9. Handling connections

When the device is connected, each device will have its own ipvthsocket. The data sharing between devices can be completed.
First, the getInputStream () and getOutputStream () methods are called to obtain the input and output streams.
Then, you can call the read (byte []) and write (byte []) Methods to read or write data.
Conclusion details: read and write operations are all congested calls, and a dedicated thread is required for handling.

10. permission settings
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /><uses-permissionandroid:name="android.permission.BLUETOOTH" />

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.