简体   繁体   中英

Android Bluetooth headset connection

I am new to Android Platform. I am working with an application requires integration of Bluetooth. The requirement is instead of manually connecting and disconnecting a Bluetooth headset(HSP profile),Connection and disconnection should be possible within the application.Is it possible to connect and disconnect the device in Android devices running OS 4.2 ,4.3 and 4.4.If any one has a solution for this issue,Please advise me for the same.

It is possible, but sometimes not that simple.

To connect, start by checking whether or not the device you are running on has BT support at all:

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter==null) {
   // device not support BT
}

If not - gracefully disable the BT portion of your app and move on.

If supported, check whether or not it is currently enabled (remember, the user can turn BT on & off as with other communication channels):

boolean isEnabled = bluetoothAdapter.isEnabled(); // Equivalent to: getBluetoothState() == STATE_ON

And, if not enabled, allow the user to turn it on by firing an ACTION_REQUEST_ENABLE intent:

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, ENABLE_BT_CODE);

Once you are clear in terms of availability, perform lookup for the specific device you aim for. It is always a good idea to start with the bonded device list maintained by Android:

Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();

for (BluetoothDevice device: pairedDevices) {
    if (device is the one we look for) {
       return device;
    }
}

If not, you will need to issue a BT discovery command.

Discovery must never be performed on the UI thread, so please spawn a thread (use AsyncTask, Executer, etc. to do the work).

Discovery should not be performed when a BT connection operation is still taking place. The impact on the device resources will be too high.

Start by setting your discovery receiver:

discoveryReceiver = new BroadcastReceiver() {
    private boolean wasFound = false;
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        System.out.println(action);
        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            discoveryStatus = STARTED;
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            discoveryStatus = FINISHED;
        }
        else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device is what we look for) {
                stopDiscovery(context);
            }
        }
    }
};
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(discoveryReceiver, filter);

And follow with a start off command:

boolean started = bluetoothAdapter.startDiscovery(); //async call!
if (!started) {
   // log error
}

Once you find your device, you will then need to create a dedicated BT socket:

BluetoothSocket clientSocket = null;
try {
    if (secureMode == SECURE) {
        clientSocket = device.createRfcommSocketToServiceRecord(serviceUuid);
    }
    else { // INSECURE
        clientSocket = device.createInsecureRfcommSocketToServiceRecord(serviceUuid);
    }
    if (clientSocket == null) {
       throw new IOException();
    }

} catch (IOException e) {
    // log error
}

Followed by connect command:

   clientSocket.connect(context);

Once connect returns, you can transmit data back & forth the way you do with sockets and when done:

  clientSocket.close(context);

The above depicts the general flow. In many cases your work will be harder:

You will use different socket generation methods for secure vs. insecure BT modes. You will use different methods to interrogate the device for supported UUIDs. You may also sometimes have to resort to reflection to activate hidden services eg getUuids() for Android < ver 15. And the list goes on.

It makes sense, especially for a beginner, to use a tool for this job.

My favorite (I am biased, I wrote it..) is BTWiz which will encapsulate the above flow from you and will also provide you with a simple interface for async IO. Feel free to try it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM