Reputation: 21862
I'm trying to determine the preferred way for programmatically enabling bluetooth on Android. I've found that either of the following techniques works (at least on Android 4.0.4...):
public class MyActivity extends Activity {
public static final int MY_BLUETOOTH_ENABLE_REQUEST_ID = 6;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, MY_BLUETOOTH_ENABLE_REQUEST_ID);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MY_BLUETOOTH_ENABLE_REQUEST_ID) {
if (resultCode == RESULT_OK) {
// Request granted - bluetooth is turning on...
}
if (resultCode == RESULT_CANCELED) {
// Request denied by user, or an error was encountered while
// attempting to enable bluetooth
}
}
}
or...
BluetoothAdapter.getDefaultAdapter().enable();
The former asks the user for permission prior to enabling while the latter just silently enables bluetooth (but requires the "android.permission.BLUETOOTH_ADMIN" permission). Is one or the other old/obsolete and/or is one technique only available on some devices? or is it just a matter of personal preference as to which I use?
Upvotes: 7
Views: 18996
Reputation: 482
This works for me... BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.enable();
Upvotes: 1
Reputation: 216
It is clearly mentioned in Android Doc
Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.
Both of these techniques would work. You have to choose based on your purpose and requirement. Hope it answers your questions.
Upvotes: 5
Reputation: 1050
I think this can be helpful...
https://stackoverflow.com/a/20142972/1386533
You also needs to add following permissions into the manifest file as well.
android.permission.BLUETOOTH,
android.permission.BLUETOOTH_ADMIN
Upvotes: 1