Set Bluetooth as Undiscoverable

1.7k views Asked by At

I have made an app that uses bluetooth

In the oncreate() method it enables bluetooth and sets the device visible for indefinite time

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    if(!adapter.isEnabled()) {

        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_ENABLE_BT);
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivity(discoverableIntent);
    }
}

In onDestroy() it disables the bluetooth

protected void onDestroy() {
    // TODO Auto-generated method stub
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if(adapter.isEnabled()) {
        adapter.disable();
    }
    super.onDestroy();
}

But when i enable bluetooth again manually after exiting the app, It is automatically set to discoverable for indefinite time.

How do I set the bluetooth to Undiscoverable before disabling it in the onDestroy() function

Tested on Nexus 5 only

2

There are 2 answers

5
android_Muncher On

This will enable discoverability for 1 second and will save you from being indefinitely discoverable

Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,1);
startActivity(discoverableIntent);
3
nnori On
  • There does not seem to be an intent that you can generate to make a device undiscoverable.
  • So, you need to work around this. Starting a new intent for discoverability for one second would do the trick.
  • It would bring down the discoverability time from infinity to one second which is as close as we can get to making it undiscoverable.
  • I understand that it's a hack, but there is no other way provided in the Android documentation.

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,1);
    startActivity(discoverableIntent);
    

Link to Android documentation for discoverability in bluetooth devices : http://developer.android.com/guide/topics/connectivity/bluetooth.html#EnablingDiscoverability

This is a possible duplicate of the question : Disable Bluetooth discoverable mode on Android