Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set Discoverable time without user confirmation?

I usually use this

private void ensureDiscoverable() {
    if(D) Log.d(TAG, "ensure discoverable");
    if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
    }
}

But that prompts a user confirmation. Is there a way to bypass this programmatically?

Also, I suppose there are no "news" on the "always discoverable mode" ?

like image 734
Tiago Avatar asked Jan 05 '12 12:01

Tiago


1 Answers

After some research I concluded that setting discoverable timeout without user interaction it's only possible with root access (as already suggested in the previous answer). However for someone who need that here is the necessary solution:

private void ensureBluetoothDiscoverability() {
    try {
        IBluetooth mBtService = getIBluetooth();
        Log.d("TESTE", "Ensuring bluetoot is discoverable");
        if(mBtService.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Log.e("TESTE", "Device was not in discoverable mode");
            try {
                mBtService.setDiscoverableTimeout(100);
                // mBtService.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 1000);
            } catch(Exception e) {
                Log.e("TESTE", "Error setting bt discoverable",e);
            }
            Log.i("TESTE", "Device must be discoverable");
        } else {
            Log.e("TESTE", "Device already discoverable");
        }
    } catch(Exception e) {
        Log.e("TESTE", "Error ensuring BT discoverability", e);
    }    
}


<uses-permission android:name="android.permission.WRITE_SETTINGS" />  
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

And then create a new package android.bluetooth, place two files inside IBluetooth.aidl and IBluetoothCallback.aidl and put inside the code as shown here.

This will allow to access functions that are not available on the standard API, but for some of them you will need permission to "write secure settings" (the comment line above is where you will get that exception for lack of permissions of the process/user).

like image 96
Tiago Avatar answered Sep 18 '22 10:09

Tiago