Skip to main content

android - Enable and disable Bluetooth programmatically


<?xml version="1.0" encoding="utf-8"?>
        android:text="Bluetooth support?"
        android:text="Bluetooth is enabled?"
        android:text="Enable Bluetooth"
        android:text="Disable Bluetooth"


import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private RelativeLayout mRelativeLayout;
    private TextView mTextView;

    private Button mButtonSupport;
    private Button mButtonState;
    private Button mButtonEnable;
    private Button mButtonDisable;
    private BluetoothAdapter mBluetoothAdapter;

    private static final int REQUEST_ENABLE_BT = 1;

    protected void onCreate(Bundle savedInstanceState) {

        // Get the application context
        mContext = getApplicationContext();

        // Get the Resources
        mResources = getResources();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(;
        mTextView = (TextView) findViewById(;
        mButtonSupport = (Button) findViewById(;
        mButtonState = (Button) findViewById(;
        mButtonEnable = (Button) findViewById(;
        mButtonDisable = (Button) findViewById(;

            In order to use Bluetooth features in your application, you must declare the Bluetooth
            permission BLUETOOTH. You need this permission to perform any Bluetooth communication,
            such as requesting a connection, accepting a connection, and transferring data.

            If you want your app to initiate device discovery or manipulate Bluetooth settings,
            you must also declare the BLUETOOTH_ADMIN permission.

                Represents the local device Bluetooth adapter. The BluetoothAdapter lets you perform
                fundamental Bluetooth tasks, such as initiate device discovery, query a list of
                bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address,
                and create a BluetoothServerSocket to listen for connection requests from other
                devices, and start a scan for Bluetooth LE devices.

            public static synchronized BluetoothAdapter getDefaultAdapter ()
                Get a handle to the default local Bluetooth adapter.
                Currently Android only supports one Bluetooth adapter, but the API could be extended
                to support more. This will always return the default adapter.

                the default local adapter, or null if Bluetooth is not supported on
                this hardware platform

        // Initialize a new instance of BluetoothAdapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // Button to check the device support Bluetooth or not
        mButtonSupport.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if(mBluetoothAdapter != null){
                    // The device support Bluetooth
                    mTextView.setText("Device support Bluetooth");
                    // The device does not support Bluetooth
                    mTextView.setText("Device does not support Bluetooth");

        // Button to get device Bluetooth current state
        mButtonState.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                    public boolean isEnabled ()
                        Return true if Bluetooth is currently enabled and ready for use.
                        Equivalent to: getBluetoothState() == STATE_ON

                        Requires BLUETOOTH

                        true : if the local adapter is turned on
                    // Bluetooth is enabled
                    mTextView.setText("Bluetooth enabled");
                }else {
                    // Bluetooth is disabled
                    mTextView.setText("Bluetooth disabled");

        // Button to enable the device Bluetooth
        mButtonEnable.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                        public static final String ACTION_REQUEST_ENABLE
                            Activity Action : Show a system activity that allows the user to turn on Bluetooth.

                            This system activity will return once Bluetooth has completed turning on,
                            or the user has decided not to turn Bluetooth on.

                            Notification of the result of this activity is posted using the
                            onActivityResult(int, int, Intent) callback. The resultCode will be
                            RESULT_OK if Bluetooth has been turned on or RESULT_CANCELED if the user
                            has rejected the request or an error has occurred.

                            Applications can also listen for ACTION_STATE_CHANGED for global
                            notification whenever Bluetooth is turned on or off.

                            Requires BLUETOOTH

                            Constant Value : "android.bluetooth.adapter.action.REQUEST_ENABLE"
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

                        public void startActivityForResult (Intent intent, int requestCode)
                            Same as calling startActivityForResult(Intent, int, Bundle) with no options.

                            intent : The intent to start.
                            requestCode : If >= 0, this code will be returned in onActivityResult()
                                when the activity exits.

                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

                        A dialog will appear requesting user permission to enable Bluetooth.
                        If the user responds "Yes," the system will begin to enable Bluetooth and
                        focus will return to your application once the process completes (or fails).

                        The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a
                        locally defined integer (which must be greater than 0), that the system
                        passes back to you in your onActivityResult() implementation as the
                        requestCode parameter.

                        If enabling Bluetooth succeeds, your activity receives 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 is RESULT_CANCELED.

        // Button to disable the device Bluetooth
        mButtonDisable.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                        public boolean disable ()
                            Turn off the local Bluetooth adapter—do not use without explicit user
                            action to turn off Bluetooth.

                            This gracefully shuts down all Bluetooth connections, stops Bluetooth
                            system services, and powers down the underlying Bluetooth hardware.

                            Bluetooth should never be disabled without direct user consent. The
                            disable() method is provided only for applications that include a user
                            interface for changing system settings, such as a "power manager" app.

                            This is an asynchronous call: it will return immediately, and clients
                            should listen for ACTION_STATE_CHANGED to be notified of subsequent
                            adapter state changes. If this call returns true, then the adapter
                            state will immediately transition from STATE_ON to STATE_TURNING_OFF,
                            and some time later transition to either STATE_OFF or STATE_ON. If this
                            call returns false then there was an immediate problem that will prevent
                            the adapter from being turned off - such as the adapter already being
                            turned off.

                            Requires the BLUETOOTH_ADMIN permission

                            true : to indicate adapter shutdown has begun, or false on immediate error
                    // If enabled then disable it
AndroidManifest.xml [permissions]

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

Popular posts from this blog

Android Popup Window Example

activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="" xmlns:tools="" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#f5f1e0" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Popup Window" /> </RelativeLayout> res/layout/custom_layout.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="" android:id="@+id/rl_custom_layout" …

How to add a hint to Spinner in Android

activity_main.xml <RelativeLayout xmlns:android="" xmlns:tools="" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context=".MainActivity" android:background="#60c4ff" > <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> spinner_item.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:textStyle="italic" …

How to create a round/circle Button in Android

activity_main.xml code snippet <Button android:id ="@+id/push_button" android:layout_width="150dp" android:layout_height="150dp" android:text="Round Button" android:background="@drawable/button_bg_round" android:padding="15dp" /> res/drawable/button_bg_round.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android=""> <item> <shape android:shape="oval"> <stroke android:color="#1E90FF" android:width="5dp" /> <solid android:color="#87CEEB"/> <size android:width="150dp" android:height="150dp"/> </shape> </item> </selector> More android examples How to set Button fontHow to change Button font programmaticallyHow to set Button text style to bold and italic…