开发者

How to turn on bluetooth on button click

开发者 https://www.devze.com 2023-03-17 03:13 出处:网络
In my application, I need to turn on bluetooth of my device on a b开发者_Go百科utton click. How can I achieve that? An example will be really helpful. Also, what permissions I require to include in my

In my application, I need to turn on bluetooth of my device on a b开发者_Go百科utton click. How can I achieve that? An example will be really helpful. Also, what permissions I require to include in my mainfest.xml for the same?


Following are code excerpts from android documentation on Bluetooth

In the manifest file for permissions:

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

Source code to enable Bluetooth

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}

if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

If enabling Bluetooth succeeds, your Activity will receive the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code will be RESULT_CANCELED.


Turn on Bluetooth in Android it's not difficult.But you must pay attention to some details.There are 3 kinds of methods to turn on Bluetooth in Android.

1.Force to open Bluetooth.

In order to get the default bluetooth adapter, ie use BluetoothAdapter.getDefaultAdapter(); You need this permission:

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

In order to force to open Bluetooth, ie use BluetoothAdapter.enable(); You need this permission:

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

Here is a code sample

/**
 * Bluetooth Manager
 * 
 * @author ifeegoo www.ifeegoo.com
 * 
 */
public class BluetoothManager
{

    /**
     * Whether current Android device support Bluetooth.
     * 
     * @return true:Support Bluetooth false:not support Bluetooth
     */
    public static boolean isBluetoothSupported()
    {
        return BluetoothAdapter.getDefaultAdapter() != null ? true : false;
    }

    /**
     * Whether current Android device Bluetooth is enabled.
     * 
     * @return true:Bluetooth is enabled false:Bluetooth not enabled
     */
    public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();

        if (bluetoothAdapter != null)
        {
            return bluetoothAdapter.isEnabled();
        }

        return false;
    }

    /**
     * Force to turn on Bluetooth on Android device.
     * 
     * @return true:force to turn on Bluetooth success 
     * false:force to turn on Bluetooth failure
     */
    public static boolean turnOnBluetooth()
    {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();

        if (bluetoothAdapter != null)
        {
            return bluetoothAdapter.enable();
        }

        return false;
    }
}

The method above to turn on Bluetooth will not tell the user whether you turn on Bluetooth success or not.When you call the method enable(), you will not turn on Bluetooth 100%.Because of the reason of some security apps refuse you to do this and so on.You need to pay attention to the return value of the method enable().

The official api of the method enable() tells us that :

Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a “power manager” app.

So it's not suitable for you to turn on Bluetooth by the method enable() unless you make the user know what you will do.

2.Use System Alert to remind users that you will turn on Bluetooth by startActivityForResult.

this.startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON) 
need this permission:
<uses-permission android:name="android.permission.BLUETOOTH" />


public class MainActivity extends Activity
{
    /**
     * Custom integer value code for request to turn on Bluetooth,it's equal            
      *requestCode in onActivityResult.
     */
    private static final int REQUEST_CODE_BLUETOOTH_ON = 1313;

    /**
     * Bluetooth device discovery time,second。
     */
    private static final int BLUETOOTH_DISCOVERABLE_DURATION = 250;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_main);

        if ((BluetoothManager.isBluetoothSupported())
                && (!BluetoothManager.isBluetoothEnabled()))
        {
            this.turnOnBluetooth();
        }
    }

    /**
     * Use system alert to remind user that the app will turn on Bluetooth
     */
    private void turnOnBluetooth()
    {
        // request to turn on Bluetooth
        Intent requestBluetoothOn = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);

        // Set the Bluetooth discoverable.
        requestBluetoothOn
                .setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // Set the Bluetooth discoverable time.
        requestBluetoothOn.putExtra(
                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                BLUETOOTH_DISCOVERABLE_DURATION);

        // request to turn on Bluetooth
        this.startActivityForResult(requestBluetoothOn,
                REQUEST_CODE_BLUETOOTH_ON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON)
        {
            switch (resultCode)
            {
                // When the user press OK button.
                case Activity.RESULT_OK:
                {
                    // TODO 
                }
                break;

                // When the user press cancel button or back button.
                case Activity.RESULT_CANCELED:
                {
                    // TODO 
                }
                break;
                default:
                break;
            }
        }
    }
}

This is a better way for you to turn on Bluetooth on Android.

3.Guide users to the system Bluetooth settings to turn on Bluetooth by themselves.

// Guide users to system Bluetooth settings to turn on Bluetooth by himselves.
this.startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));

In my app.Considering the code logical and also the user experience, I use the follow steps to turn on Bluetooth:

1.use enable() to turn on Bluetooth.But I will tell the users that I will turn on Bluetooth, if they allow me to do this, I will call enable() to turn on Bluetooth.This is better than call the system alert, because we can control the content to remind user. You must pay attention that it's not 100% to turn on Bluetooth by enable() , some security apps or other reasons refuse you to do this.But we can estimate that whether we turn on Bluetooth success or not by the return value of the method enable().

2.If the method enable() return false,then we use startActivityForResult to remind users that we will turn on Bluetooth.

3.If the step 2 will not work by some reasons, you can guide the users to go to the system Bluetooth settings to turn on Bluetooth by themselves.

Add more:since Android 6.0 we need to deal with the permission of Bluetooth.


This solution will help you Android Bluetooth. But for details about the Bluetooth usage with Android along with manifest.xml you need to see this Android Bluetooth.

For permission you need.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号