Hello everyone! π
In this article, I will explain how to enable Bluetooth on an Android device using Java. This method is compatible with both newer and older Android devices.
Bluetooth Permission π±π
Target Android 12 or Higher
Declare the Bluetooth Connect permission in the manifest file and request at runtime.
<manifest>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"
</manifest>
requestPermissions(new String[]{android.Manifest.permission.BLUETOOTH_CONNECT},100);
Target Android 11 or Lower
Declare the Bluetooth permission in the manifest file.
<uses-permission android:name="android.permission.BLUETOOTH"/>
Request To Enable Bluetooth πΆ
ActivityResultLauncher
First, declare and initialize the ActivityResultLauncher to handle the result of enabling Bluetooth.
Note: Register the ActivityResultLauncher inside the onCreate() lifecycle method.
// Declare the ActivityResultLauncher
ActivityResultLauncher<Intent> enableBtLauncher;
// Initialize the ActivityResultLauncher to handle the result
enableBtLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
// Bluetooth is enabled, handle accordingly
// You can perform further actions here
} else {
// Bluetooth is not enabled or user canceled
// You may want to handle this case
}
});
Intent
Now create an Intent object with the action to enable Bluetooth and use the ActivityResultLauncher to launch the intent.
// Create an intent to prompt the user to enable Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// Launch the Bluetooth enabling activity and register a callback to handle the result
enableBtLauncher.launch(enableBtIntent);
The above code can be used as a trigger.
If the device is running Android 12 or above, you should check whether the user has granted the Bluetooth Connect permission before executing the above code.
thatβs all.
Hope you found this article helpful. Happy coding!