Helper to turn Bluetooth on. - Android Bluetooth

Android examples for Bluetooth:Turn On bluetooth

Description

Helper to turn Bluetooth on.

Demo Code


import android.bluetooth.BluetoothAdapter;
import android.util.Log;

public class Main {
  protected static String TAG = "BluetoothTestUtils";
  static final int POLL_TIME = 500;
  static final int ENABLE_TIMEOUT = 5000;

  /**/*  w  ww  .j  a  v a 2 s  .  c om*/
   * Helper to turn BT on. This method will either fail on an assert, or return
   * with BT turned on. Behavior of getState() and isEnabled() are validated along
   * the way.
   */
  public static void enableBt(BluetoothAdapter adapter) {
    if (adapter.getState() == BluetoothAdapter.STATE_ON) {
      return;
    }
    adapter.enable();
    for (int i = 0; i < ENABLE_TIMEOUT / POLL_TIME; i++) {
      int state = adapter.getState();
      switch (state) {
      case BluetoothAdapter.STATE_ON:
        Log.i(TAG, "Bluetooth enabled...");
        return;
      case BluetoothAdapter.STATE_OFF:
        Log.i(TAG, "STATE_OFF: Still waiting for enable to begin...");
        break;
      default:
        Log.i(TAG, "Status is: " + state);
        break;
      }
      try {
        Thread.sleep(POLL_TIME);
      } catch (InterruptedException e) {
      }
    }

  }
}

Related Tutorials