Search code examples
androideclipsebluetoothtogglebutton

Toggling Bluetooth on and off?


Is there a simple tutorial or dose anyone have code to toggle Bluetooth on and off using a Toggle-button in eclipse building for android?

If anyone can help that will be greatly appreciated.

-Thanks in advance.


Solution

  • You'll need

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

    in your manifest file, and variables like:

    private final integer REQUEST_ENABLE_BT = 1;
    

    and

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean hasBluetooth = (mBluetoothAdapter == null);
    

    so that in your OnCreate you can do something like:

    final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
    togglebutton.setOnClickListener(new OnClickListener()
    {
      public void onClick(View v)
      {
        // Perform action on clicks
        if (togglebutton.isChecked())
        {
          if (hasBluetooth && !mBluetoothAdapter.isEnabled())
          {
            // prompt the user to turn BlueTooth on
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          }
        }
        else
        {
          if (hasBluetooth && mBluetoothAdapter.isEnabled())
          {
            // you should really prompt the user for permission to turn
            // the BlueTooth off as well, e.g., with a Dialog
            boolean isDisabling = mBluetoothAdapter.disable();
            if (!isDisabling)
            {
               // an immediate error occurred - perhaps the bluetooth is already off?
            }
          }
        }
      }
    });
    

    where the user response to the "turn bluetooth on" prompt is caught in

    protected void onActivityResult (int requestCode, int resultCode, Intent data)
    {
      if ((requestCode == REQUEST_ENABLE_BT) && (resultCode == RESULT_OK))
      {
        boolean isEnabling = mBluetoothAdapter.enable();
        if (!isEnabling)
        {
          // an immediate error occurred - perhaps the bluetooth is already on?
        }
        else if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON)
        {
          // the system, in the background, is trying to turn the Bluetooth on
          // while your activity carries on going without waiting for it to finish;
          // of course, you could listen for it to finish yourself - eg, using a
          // ProgressDialog that checked mBluetoothAdapter.getState() every x
          // milliseconds and reported when it became STATE_ON (or STATE_OFF, if the
          // system failed to start the Bluetooth.)
        }
      }
    }