Search code examples
androidbluetooth-lowenergyandroid-bluetoothonactivityresultestimote

Android: force bluetooth


Is there a way to force bluetooth on?

all I've found so far is this (using the estimote sdk, which I'm working with):

// Check if device supports Bluetooth Low Energy.
if (!beaconManager.hasBluetooth()) {
    Toast.makeText(this, "Device does not have Bluetooth Low Energy", Toast.LENGTH_LONG).show();
    return;
}

// If Bluetooth is not enabled, let user enable it.
if (!beaconManager.isBluetoothEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} 
else {
    connectToBlueTooth();
}

And then in the onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_ENABLE_BT) {
        if (resultCode == Activity.RESULT_OK) {
            connectToBlueTooth();
        }
        else {
            Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show();
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

But this asks to the user if he wants to turn on bluetooth... but is there a way to turn it on without asking the user?

And, if there is no way to do it, how can I use this technique outside of an activity?

Thanks


Solution

  • Try BluetoothAdapter like this:

    BluetoothAdapter.getDefaultAdapter().enable();