0

I am using the below code as per requirement from client to internally enable Bluetooth and disable it when exit the application.

if (!bluetoothAdapter.isEnabled()) {
            MMLogger.logInfo(MMLogger.LOG_BLUETOOTH, "BluetoothSyncController - Bluetooth was OFF, so Turn it ON");
            bluetoothAdapter.enable();
            try {
                Thread.sleep(WAIT_FOR_SOMETIME_TO_START_BLUETOOTH);  
            } catch (InterruptedException ignore) {
            }
            MMLogger.logInfo(MMLogger.LOG_BLUETOOTH, "BluetoothSyncController - Bluetooth turned ON");
        }

IS there any standard time for WAIT_FOR_SOMETIME_TO_START_BLUETOOTH ? I mean any documentation ?

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68

1 Answers1

0

You might try this answer. There seem to be some standard bluetooth events and handlers out there.

From that source: There are events that your activity can manage such as

STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF

and you can catch these with a BroadcastReciever. First you want to make sure that you grant permissions for bluetooth inside of your manifest with:

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

Then you can create a custom broadcast receiver that has the following onReceive():

@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();

    if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
        final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
        switch(state) {
            case BluetoothAdapter.STATE_OFF:
                ..
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                ..
                break;
            case BluetoothAdapter.STATE_ON:
                ..
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                ..
                break;
        }

    }
}

Then instead of making a thread to wait you can have a receive event trigger the code you want to run. For more info on using a BroadcastReciever, see the link I provided or go straight to the android documentation.

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/18544329) – Yoh Deadfall Jan 17 '18 at 15:29
  • Thank you for the feedback! I'm new here so I haven't quite learned all the etiquette yet. – Matthew Flathers Jan 17 '18 at 15:54