Android Bluetooth Summary

Keywords: Android socket network Java

Android Bluetooth

Basic concepts

  • Bluetooth is a short distance (10m) wireless communication technology standard. Bluetooth protocol is divided into four layers: core protocol layer, cable substitution protocol layer, telephone control protocol layer and other protocol layer adopted. The most important of these four protocols is the core protocol. The core protocol of Bluetooth includes four parts: baseband, link management, logical link control and adaptation protocol. Link Management (LMP) is responsible for the establishment of Bluetooth component connections. Logical Link Control and Adaptation Protocol (L2CAP) is located on the baseband protocol layer and belongs to the data link layer. L2CAP is an adaptation protocol that shields the baseband protocol for high-level transmission and application layer protocols.

  • The Android platform provides support for Bluetooth's communication stack, allowing devices and other devices to transmit data wirelessly. The application layer calls Bluetooth related functions through Android API s, which enable programs to wirelessly connect to Bluetooth devices and have the characteristics of P2P or multi-terminal wireless connections.

  • Wireless headset, wireless mouse, wireless keyboard

  • Bluetooth functions:

    1. Scanning other Bluetooth devices
    2. Query Bluetooth adapters for matching Bluetooth devices
    3. Establishing RFCOMM Channels (in fact, Nima's authentication)
    4. Link to other devices through service search
    5. Data transmission with other devices
    6. Manage multiple connections
  • Bluetooth connection must require:

    1. Turn on Bluetooth
    2. Find nearby paired or available devices
    3. Connecting device
    4. Data Interaction between Devices

Bluetooth API

Code distribution

packages/apps/Bluetooth/

  • Bluetooth application, mainly about Bluetooth application protocol performance code, including opp, hfp, hdp, a2dp, pan and so on.

frameworks/base/core/Java/android/server/

  • After 4.2, although this directory still exists, the code in it has been transferred to the application layer, which is the previous directory, so Bluetooth on 4.2.2 can be ignored here.

framework/base/core/java/android/bluetooth

  • The code in this directory is more like a bridge. It's important to have some classes for java layer, and the corresponding aidl files to contact the C and C++ code.

kernel\drivers\bluetoothBluetooth

  • Specific protocol implementation. Including hci,hid, rfcomm,sco,SDP and other protocols

kernel\net\bluetooth Linux kernel

  • Bluetooth device driver for various interfaces. For example: USB interface, serial port, etc., the two directories above the kernel may not be visible, but there will be.

external\bluetooth\bluedroid

  • Official Bluetooth Protocol Stack

system\bluetoothBluetooth

  • Adaptation layer code, similar to framework, is a tool for concatenating framework and protocol stack.

Key class

/frameworks/base/core/java/android/bluetooth/

  • Bluetooth Adapter represents the local Bluetooth adapter (Bluetooth transmitter) and is the entry point for all Bluetooth interactions. It can search for other Bluetooth devices, query the list of matched devices, create Bluetooth Devices through known MAC addresses, and create Bluetooth Server Socket to listen for communications from other devices.
  • Bluetooth Device represents a remote Bluetooth device, using it to request remote Bluetooth device connection or to obtain the name, address, type and binding status of remote Bluetooth device. The information is encapsulated in Bluetooth socket.
  • Bluetooth Socket represents a Bluetooth socket interface (similar to sockets in tcp). It is the connection point for applications to communicate with other Bluetooth devices through input and output streams.
  • Bluetooth Server Socket represents opening a service connection to listen for possible incoming connection requests (belonging to the server side). In order to connect two Bluetooth devices, one device must open a service socket as a server. When the remote device initiates a connection request and is already connected, the Bluebooth server socket class will return a Bluetooth socket.
  • Bluetooth Class describes the profile of a device or roughly what services Bluetooth on that device can provide, but it is not trusted. For example, a device is a telephone, computer or handheld device; a Bluebooth server socket device can provide audio/telephony services, etc. It can be used for some UI prompts.
  • Bluetooth Profile Bluetooth Protocol
  • Bluetooth Headset provides Bluetooth headset support for mobile phones. This includes both Bluetooth headset and hands-free (V1.5) mode.
  • Bluetooth A2dp defines high-quality audio that can be transferred from one device to another Bluetooth connection. "A2DP" represents the advanced audio allocation mode.
  • Bluetooth Health represents Bluetooth services controlled by medical equipment configuration agent
  • Bluetooth Health Callback is an abstract class that implements Bluetooth Health callbacks. You must extend this class and implement a callback method to receive changes in the registration status and Bluetooth channel status of the updated application.
  • Bluetooth Health App Configuration represents the configuration of an application, and Bluetooth medical third-party applications register to communicate with remote Bluetooth medical devices.
  • Bluetooth Profile. Service Listener has an interface when they notify Bluetooth Profile IPX customers when they are connected to or disconnected from the service (that is, running a specific configuration file, internal service).

\packages\apps\Settings\src\com\android\settings\bluetooth

  • It's the Bluetooth switch on and off on the Bluetooth Enabler interface.
  • Bluetooth Settings Home Interface for Managing Matching and Connecting Devices
  • Local Bluetooth Manager provides a simple invocation interface on the Bluetooth API, which is just the beginning.
  • Cached Bluetooth Device describes the classes of Bluetooth devices and re-encapsulates Bluetooth Device
  • Bluetooth Pairing Dialog dialog box with matching prompts

/packages/apps/Phone/src/com/android/phone/

  • Bluetooth Phone Service must have something to do with the phone in the phone directory, which Bluetooth will use to answer and hang up the phone.

/packages/apps/Bluetooth/src/com/android/bluetooth/

The 4.2 Bluetooth directory has changed. In the 4.1 and previous codes, only the code of the packages layer is the code of the application related to the opp protocol, that is, the file transfer part. The code of the 4.2 code application layer is much richer. According to the specific Bluetooth application protocol, it can be divided into the following folders (here is a brief explanation for some terms of Bluetooth).
- btservice, the previous description of AdapterService.java, you should be able to guess something about the directory of the basic operations of Bluetooth, and everything starts from that.

- AdapterService (code after 4.2) Bluetooth opens, closes, scans, pairs will come here, in fact, more accurately, it replaces BluetoothService.java before 4.1, the original work is completed by this class.
  • a2dp (Advanced Audio Distribution Profile) Advanced Audio Transmission Mode, Bluetooth Stereo, and Bluetooth Headset Listening about those.
  • avrcp Audio/Video Remote Control Configuration File is used to pause while listening to songs and select up and down songs.
  • hdp (Health Device Profile) Bluetooth medical device model, can create Bluetooth-enabled medical devices, using Bluetooth communications applications, such as heart rate monitors, blood, thermometers and scales.
  • hfp (Hands-free Profile) allows Bluetooth devices to control the phone, such as answering, hanging up, rejecting, voice dialing, etc. The rejection and voice dialing depends on whether Bluetooth headset and phone support.
  • pbap (Phonebook Access Profile) telephone directory access protocol
  • Hidden (The Human Interface Device) human-computer interaction interface, Bluetooth mouse keyboard and so on. This protocol is adapted from USB HID Protocol.
  • opp (Object Push Profile) object storage specification, the most common, file transfer is using this protocol.
  • pan (Personal Area Network) describes how two or more Bluetooth devices form an instant network, related to the network, as well as serial port function (SPP), dial-up network function (DUN).

android 4.2's Bluetooth application layer has more code, although some directories have no specific code, but it's not clear which version will be updated, just like 4.0 added the hdp medical part. In addition, the JNI code originally in the framework has also been moved to packages/apps/bluetooth.

Main method

  • Bluetooth Adapter

    • getDefaultAdapter() Gets the local Bluetooth adapter
    • setName(String name) Sets Bluetooth Name
    • disable() turn off Bluetooth
    • enable() Open Bluetooth
    • isEnabled() to determine whether Bluetooth is turned on
    • getName() gets the name of the local Bluetooth
    • getAddress() gets the address of the local Bluetooth adapter
    • getBondedDevices() Gets the Bluetooth device that has been bound
    • getRemoteDevice(byte[] address) Gets a remote Bluetooth device
    • Get RemoteDevice (String address) to get remote Bluetooth devices
    • startDiscovery() starts searching for Bluetooth near Dodo
    • cancelDiscovery() Stops the Task currently searching for Bluetooth
    • Listen UsingInsecureRfcommWithService Record (String name, UUID uuid) to create Bluetooth Server Socket
  • Bluetooth Device

    • createBond() Bluetooth pairing (low version is not supported, >= api19)
    • Create Rf commSocket To Service Record (UUID uuid) Create Bluetooth Socket
    • getBondState() gets the paired state
    • getAddress() gets the address of the remote Bluetooth adapter
    • getName() gets the name of remote Bluetooth
  • Bluetooth Server Socket
    There are only three methods and two overloads in this class. The difference between the two overloads is that the latter method specifies the outdated time. It should be noted that when these two methods are executed, the thread will be blocked until the client's request is received (or after the expiration), which should be run in a new thread!

    • close() closed
    • connect() connection
    • isConnected() Judges the current connection status
    • accept() receives requests
    • accept(int timeout) receives requests
  • Bluetooth Socket (Data Transfer Client)

    • close() closed
    • connect() connection
    • getInptuStream() Gets the input stream
    • getOutputStream() Gets the output stream
    • getRemoteDevice() Gets the remote device, which means the remote Bluetooth device that gets the Bluetooth Socket specified connection

Bluetooth operation

Turn Bluetooth on and off

There are two ways to turn Bluetooth on:

First, call the system dialog box directly to start Bluetooth:

Adding the required permissions to the AndroidManifest.xml file does not require dynamic authorization for higher versions:

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

Then, in the code, execute:

startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);

If you don't want users to see the dialog box, then we can choose the second way to silently open Bluetooth.

2. Open silently, there will be no dialog box of method one:

Similarly, add the required permissions to the AndroidManifest.xml file:

<!-- Adapted 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 permissions that include Dangerous Permissions, we need to do dynamic authorization processing in Java code:

private static final int REQUEST_BLUETOOTH_PERMISSION=10;

private void requestBluetoothPermission(){
    //Judging System Version
    if (Build.VERSION.SDK_INT >= 23) {
        //Check whether the current app has a permission
        int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, 
                Manifest.permission.ACCESS_COARSE_LOCATION);
        //Determine whether this permission has been authorized
        if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
            //Determine whether you need to explain to the user and why you want to apply for this privilege
            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 {
    }
}

Then we can silently turn on Bluetooth:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable(); //open

Turn off Bluetooth

if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable();
}

Search for Bluetooth Devices

Search is divided into active search and passive search.

Passive Search

if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) 
{
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    // Set the discovery time, the maximum is 3600 seconds, 0 means that the device can always be found (less than 0 or more than 3600 will be automatically set to 120 seconds)
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
    activity.startActivity(discoverableIntent);
}

II. Active Search

Create Bluetooth Adapter Object

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

Let's first get and display the list of Bluetooth devices that have been paired up.

/*
 * List of Paired Devices
 */
private ListView mBoundDevicesLv;
/**
 * Display a list of matched devices
 */
private void showBoundDevices() {
    List<Map<String, String>> mBoundDevicesList = new ArrayList<>();
    Set<BluetoothDevice> boundDeviceSet = mBluetoothAdapter.getBondedDevices();
    for (BluetoothDevice boundDevices : boundDeviceSet) {
        Map<String, String> mBoundDevicesMap = new HashMap<>();
        mBoundDevicesMap.put("name", boundDevices.getName());
        mBoundDevicesMap.put("address", boundDevices.getAddress());
        mBoundDevicesList.add(mBoundDevicesMap);
    }
    SimpleAdapter mSimpleAdapter = new SimpleAdapter(MainActivity.this, mBoundDevicesList,
            android.R.layout.simple_list_item_2,
            new String[]{"name", "address"},
            new int[]{android.R.id.text1, android.R.id.text2});
    mBoundDevicesLv.setAdapter(mSimpleAdapter);
}

Start search

if (mBluetoothAdapter == null) {
    LogUtil.e(TAG, "Bluetooth is not supported on devices");
}
// Turn on Bluetooth       
if (!mBluetoothAdapter.isEnabled()) {
    BluetoothAdapter.enable();
    mBluetoothAdapter.cancelDiscovery();
}
// Looking for Bluetooth devices, android will broadcast the devices it finds       
while (!mBluetoothAdapter.startDiscovery()) {
    LogUtil.e(TAG, "Attempt failed");
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }   
}

Broadcast Receiver Defining Search Results

// Setting up broadcast information filtering
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);//Each time a device is searched, a broadcast is sent.
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//Send the broadcast when all searches are completed
filter.setPriority(Integer.MAX_VALUE);//set priority
registerReceiver(receiver, filter);// Register Bluetooth Search Broadcast Receiver to receive and process search results

The broadcasting receivers searching for Bluetooth devices are as follows:

/**
 * Searched set of devices
 */
private List<Map<String, String>> devices = new ArrayList<>();
/**
 * List of devices found
 */
private ListView mDevicesLv;
/**
 * Define Broadcasting 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)) {
            ToastUtil.showToast(MainActivity.this, "Showing Devices");
                // Getting device objects from Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Define a Map to load Bluetooth device name and address
                Map<String, String> deviceMap = new HashMap<>();
                // Filter paired and duplicated Bluetooth devices
                if ((device.getBondState() != BluetoothDevice.BOND_BONDED) && isSingleDevice(device)) {
                    deviceMap.put("name", device.getName() == null ? "null" : device.getName());
                    deviceMap.put("address", device.getAddress());
                    devices.add(deviceMap);
                }
                // Display the list of Bluetooth devices found
                mDevicesLv.setVisibility(View.VISIBLE);
                // Loading device
                showDevices();
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            //The search has been completed
        }
    }
};Define the server-side thread class:

/**
 * Determine whether the device exists
 */
private boolean isSingleDevice(BluetoothDevice device) {
    if (devices == null) {
        return true;
    }
    for (Map<String, String> mDeviceMap : devices) {
        if ((device.getAddress()).equals(mDeviceMap.get("address"))) {
            return false;
        }
    }
    return true;
}

/**
 * Display the list of devices searched
 */
private void showDevices() {
    SimpleAdapter mSimpleAdapter = new SimpleAdapter(MainActivity.this, devices,
            android.R.layout.simple_list_item_2,
            new String[]{"name", "address"},
            new int[]{android.R.id.text1, android.R.id.text2});
    mDevicesLv.setAdapter(mSimpleAdapter);
}

Bluetooth pairing

When we search for Bluetooth, we need to pair, because only after pairing can we connect.

In the click event of the list of devices searched above, pair up.

BluetoothDevice device = (BluetoothDevice) adapter.getItem(i);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {//Are you paired?
    connect(device);
} else {
    try {
        Method boned=device.getClass().getMethod("createBond");
        boolean isok= (boolean) boned.invoke(device);
        if(isOk) {
            connect(device);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }         
}

It should be noted that this pairing Android provides the createBond() method after API 19. However, this method was not available before API19, so it is better to use reflection compatibility.

Bluetooth UUID

 
Before making a Bluetooth connection, let's introduce a key point: two Bluetooth devices need to use the same UUID to connect. But many readers may find that there are many models of mobile phones (possibly non-Android phones) that use different programs to communicate with each other or Bluetooth. On the surface, it is almost impossible to use the same UUID between them.

The format of UUID is as follows:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

The UUID format is divided into five segments, with the same number of characters in the middle three segments, all of which are 4, the first paragraph is 8 characters, and the last paragraph is 12 characters. So UUID is actually an 8-4-4-4-4-12 string.

In fact, UUID, like TCP ports, has some default values. For example, services that simulate Bluetooth as a serial port use a standard UUID:

00001101-0000-1000-8000-00805F9B34FB

In addition, there are many standard UUIDs. The following are two standard UUIDs:

Information Synchronization Service: 00001104-0000-1000-8000-00805F9B34FB
File Transfer Service: 00001106-0000-1000-8000-00805F9B34FB

Data transmission between Bluetooth devices

Bluetooth transfers data similar to Socket. Socket and Server Socket are used to control data reading and writing between client and server in the network. Bluetooth communication is also accomplished by client and server Sockets. Bluetooth client Socket is Bluetooth Socket, Bluetooth server Socket is Bluetooth Server Socket. Both classes are in the android.bluetooth package.

Whether it is Bluetooth Socket or Bluetooth Server Socket, a UUID (Universal Unique Identifier) is needed. UUID is equivalent to the port of the Socket, and Bluetooth address is equivalent to the IP of the Socket.

Next, we begin to simulate a Bluetooth data transmission:

First, look at the client:

Define global constants:

private ListView mDevicesLv;
private BluetoothAdapter mBluetoothAdapter;
private List<Map<String, String>> devices = new ArrayList<>();
//Define a UUID at will
private final UUID MY_UUID = UUID.fromString("abcd1234-ab12-ab12-ab12-abcdef123456");
private BluetoothSocket clientSocket;
private BluetoothDevice device;  
private OutputStream os;//output stream

Next, we set the click event for the device list.

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Map<String, String> s = devices.get(i);
    String address = s.get("address");//Resolve the address
    //Active Connection with Bluetooth Server
    try {
        // If you are currently searching, cancel the search.
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        try {
            if (device == null) {
                //Access to remote devices
                device = mBluetoothAdapter.getRemoteDevice(address);
            }
            if (clientSocket == null) {
                //Create Bluetooth Socket for Client
                clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                //Start to connect Bluetooth, if there is no pairing, pop-up dialog box prompts us to pair.
                clientSocket.connect();
                //Get the output stream (client points to server output text)
                os = clientSocket.getOutputStream();
            }
        } catch (Exception e) {
        }
        if (os != null) {
            //Write information to the server
            os.write("Bluetooth Information".getBytes("utf-8"));
        }
    } catch (Exception e) {
    }
}

Second, look at the server:

The server uses another mobile phone, which receives the information sent by the mobile phone through Bluetooth and displays it.

Define global constants:

private BluetoothAdapter mBluetoothAdapter;
private AcceptThread acceptThread;
// The same UUID as the client
private final UUID MY_UUID = UUID.fromString("abcd1234-ab12-ab12-ab12-abcdef123456");
private final String NAME = "Bluetooth_Socket";
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
private InputStream is;//Input stream

Define the server-side thread class:

private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        Toast.makeText(getApplicationContext(), String.valueOf(msg.obj),
                Toast.LENGTH_LONG).show();
        super.handleMessage(msg);
    }
};

//Server listens on client's 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);
                Message msg = new Message();
                msg.obj = new String(buffer, 0, count, "utf-8");
                handler.sendMessage(msg);
            }
        }
        catch (Exception e) {
        }
    }
}

Initialize the thread class in the onCreate method and open:

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
acceptThread = new AcceptThread();
acceptThread.start();

Note that the data received using socket.getInputStream is a byte stream. Such data can not be parsed, so in many cases a byte to hexadecimal String function is needed:

public static String bytesToHex(byte[] bytes) { 
    char[] hexChars = new char[bytes.length * 2]; 
    for ( int j = 0; j < bytes.length; j++ ) {     
        int v = bytes[j] & 0xFF;     
        hexChars[j * 2] = hexArray[v >>> 4];     
        hexChars[j * 2 + 1] = hexArray[v & 0x0F]; 
    } 
    return new String(hexChars);
}

bluetooth

Introduction of Bluetooth Protocol

Since Android 3.0, Bluetooth API has included support for Bluetooth profiles.

Bluetooth profile is a wireless interface specification based on communication between Bluetooth devices.

You can complete the Bluetooth Profile interface in your class to support a Bluetooth profile.

The Android Bluetooth API completes the following Bluetooth profile:

  1. Headset profile provides Bluetooth headset support on mobile phones. Android provides the Bluetooth Headset class, which is a protocol for controlling Bluetooth Headset Service through IPC(interprocess communication). Bluetooth Headset contains both Bluetooth and Bluetooth
    Headset profile also includes Hands-Free profile, as well as support for AT commands.
  2. HFP (Hands-free Profile), hands-free mode, allows Bluetooth devices to control the phone, such as answering, hanging up, rejecting, voice dialing, etc., rejection, voice dialing depends on whether Bluetooth headset and phone support.
  3. HDP(Health Device Profile.), Bluetooth medical device model, can create Bluetooth-enabled medical devices, using Bluetooth communications applications, such as heart rate monitors, blood, thermometers and scales.
  4. AVRCP, Audio/Video Remote Control Configuration File, is used to pause while listening to songs and select the next and the next songs.
  5. A2DP(Advanced Audio Distribution Profile), advanced audio transmission mode. Android provides the Bluetooth A2dp class, a protocol that controls Bluetooth A2DP through IPC.
  6. HID (The Human Interface Device), human-computer interaction interface, Bluetooth mouse keyboard and so on. This protocol is adapted from USB HID Protocol.
  7. OPP (Object Push Profile), object storage specification, the most common, file transmission is using this protocol.
  8. PAN (Personal Area Network) describes how two or more Bluetooth devices form a real-time network, related to the network, as well as serial port function (SPP), dial-up network function (DUN).
  9. PBAP (Phonebook Access Profile), telephone directory access protocol.

The Use of Bluetooth Protocol

Here are the basic steps for using profile s:

  1. Get the default Bluetooth adapter.
  2. Use getProfileProxy() to establish a connection to profile-related protocol objects. In the following example, the profile protocol object is an example of Bluetooth Headset.
  3. Set Bluetooth Profile. Service Listener. The listener notifies the Bluetooth Profile IPC client when the client connects to or disconnects from the server.
  4. In Bluetooth Profile. Service Listener's onService Connected (), you get a handle to the profile protocol object.
  5. Once you have the profile protocol object, you can use it to monitor the status of the connection and complete other operations related to the profile.

For example, the following code snippet shows how to connect to a Bluetooth Headset protocol object to control the Headset profile:

BluetoothHeadset mBluetoothHeadset;
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener(){
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = (BluetoothHeadset) proxy;
        }
    }
    public void onServiceDisconnected(int profile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null;
        }
    }
};
// ... call functions on mBluetoothHeadset
// Close proxy connection after use.
mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset)

Posted by ready2drum on Thu, 18 Apr 2019 10:24:33 -0700