How to use Bluetooth with Android Bluetooth (details)

Source: Internet
Author: User

How to use Bluetooth with Android Bluetooth (details)
I. Communication between bluetooth devices involves four steps

Set the bluetooth device to find data transmission between devices that may or match devices in the LAN
II. Specific programming implementation 1. Start the Bluetooth function

First, call the static method getdefaadapter adapter () to obtain the Bluetooth adapter javasthadapter. If the returned result is null, the execution cannot continue. For example:

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

Second, call isEnabled () to query the current bluetooth device status. If false is returned, it indicates that the bluetooth device is not enabled. Next, You Need To encapsulate an ACTION_REQUEST_ENABLE request 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

By 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, make sure that the bluetooth device of the other party has enabled or enabled the "Discovery enable" function (the other party's device can be found on the premise that you can initiate a connection ). 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 can initialize a connection to the other device.
If you connect to the device for the first time, a paired request is automatically displayed to the user. After the device is paired, some of its basic information (mainly the name and MAC) is saved and can be read using the Bluetooth API. You can use a known MAC address to initiate a connection request to a remote Bluetooth device.
The difference between a matched device and a connected device: a good match only indicates that the other device has discovered your existence and has a common identifier, which can be connected. Connection: indicates that the current device shares an RFCOMM channel and data can be exchanged between the two. That is to say, the bluetooth device must have been paired before the RFCOMM channel is established.

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 it out:

Set
  
    pairedDevices =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());    }}
  

To create a Bluetooth connection, you only need the MAC address.

4. Scan Devices

To scan a device, you only need to call the startDiscovery () method. The scanning process lasts for about 12 seconds. For the ACTION_FOUND action, the application needs to register a BroadcastReceiver to receive 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. add (device. getName () + "\ n" + device. getAddress () ;}}; // register the broadcast receiver IntentFilter filter = new IntentFilter (descrithdevice. ACTION_FOUND); registerReceiver (mReceiver, filter); // remember to cancel the broadcast receiver when onDestroy
5. enable Discovery

If you want your device to be discovered by other devices, 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 add the EXTRA_DISCOVERABLE_DURATION field to change the enabling time (up to 300 seconds). For example:

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

After the code is run, a dialog box will pop up prompting you to enable the device to be detected (If your Bluetooth function is not enabled during this process, the system will enable it for you ), if you want to discover a connection to the remote device, you do not need to enable the device discovery function, because this function is only required when your application is used as a server.

6. Connect the device

In an application, to establish a connection between two bluetooth devices, the client and server code must be implemented (because any device must be used as a server or client ). Enable the Service to listen, and initiate a connection request (using the MAC address of the server device ). When both of them have a Bluetooth socket on the same RFECOMM channel, they can be considered connected. The server and the client use different methods or their Bluetooth sockets. When a connection is listening, the server gets a Bluetooth socket. When the customer can open an FRCOMM channel to the server, the client obtains the Bluetooth socket.
Note: during this process, if the two bluetooth devices are not paired, the android system will notify the user through a notification or dialog box. RFCOMM connection requests are blocked before the user selects the connection.

7. server connection

When you want to connect two devices, one must be used as the server (by holding an opened javasthserversocket) to listen for external connection requests, after listening, a persistent thsocket on the connection is provided to the client. After the client obtains the persistent thsocket from the persistent thserversocket, it can destroy the persistent thserversocket, unless you want to listen for more connection requests.
Follow these steps to establish a connection between a service socket and a listener:
First, call the listenUsingRfcommWithServiceRecord (String, UUID) method to obtain the javasthserversocket object. The String parameter represents the name of the service, and the UUID represents an identifier (128-Bit String ID, is equivalent to the PIN code), the UUID must be matched by both parties to establish a connection.
Next, call the accept () method to listen for possible incoming connection requests. After listening, return a Bluetooth socket javasthsocket connected.
Finally, after listening to a connection, you need to call the close () method to close the listener. (Generally, point-to-point transmission is performed between bluetooth devices)
Note: The accept () method should not be placed in the master Acitvity because it is a blocking call (the program stops there until the connection request is not listened ). The solution is to create a new thread for management. For example:

8. Client Connection

To initialize a connection to a remote device, you must first obtain a thdevice object representing the device. Use the ththdevice object to obtain the thsocket and initialize the connection. The specific steps are as follows:
Use the createRfcommSocketToServiceRecord (UUID) method in the initthdevice object to obtain the initthsocket. UUID is the matching code. Then, call the connect () method. If the remote device receives the connection, it will share the RFFCOMM channel during communication and connect will return.
Note: The conncet () method is also a blocking call. Generally, an independent thread is created to call this method. Connection to connect () should not be initiated during device discover, which will obviously slow down so that the connection fails. When data transmission is complete, only the close () method is called to close the connection, which can save resources in the system.

9. Manage connections

After the device is connected, each device has its own ipvthsocket. Data can be shared between devices.
First, you can call the getInputStream () and getOutputStream () methods to obtain the input and output streams.
Then, read or write data by calling the read (byte []) and write (byte []). method.
Implementation Details: read and write operations are both blocked calls, and a dedicated thread needs to be established for management.

10. permission settings

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.