Friday, November 27, 2015

android - Enable and disable Bluetooth programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ff35c6"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="#000"
        />
    <Button
        android:id="@+id/btn_support"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bluetooth support?"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_state"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bluetooth is enabled?"
        android:layout_below="@id/btn_support"
        />
    <Button
        android:id="@+id/btn_enable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable Bluetooth"
        android:layout_below="@id/btn_state"
        />
    <Button
        android:id="@+id/btn_disable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Disable Bluetooth"
        android:layout_below="@id/btn_enable"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
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;

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

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

        // Get the Resources
        mResources = getResources();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mButtonSupport = (Button) findViewById(R.id.btn_support);
        mButtonState = (Button) findViewById(R.id.btn_state);
        mButtonEnable = (Button) findViewById(R.id.btn_enable);
        mButtonDisable = (Button) findViewById(R.id.btn_disable);

        /*
            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.
        */

        /*
            BluetoothAdapter
                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.

            Returns
                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() {
            @Override
            public void onClick(View view) {
                if(mBluetoothAdapter != null){
                    // The device support Bluetooth
                    mTextView.setText("Device support Bluetooth");
                }else{
                    // 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() {
            @Override
            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

                    Returns
                        true : if the local adapter is turned on
                */
                if(mBluetoothAdapter.isEnabled()){
                    // 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() {
            @Override
            public void onClick(View view) {
                if(!mBluetoothAdapter.isEnabled()){
                    /*
                        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.

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

                    */
                    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() {
            @Override
            public void onClick(View view) {

                if(mBluetoothAdapter.isEnabled()){
                    /*
                        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

                        Returns
                            true : to indicate adapter shutdown has begun, or false on immediate error
                    */
                    // If enabled then disable it
                    mBluetoothAdapter.disable();
                }
            }
        });
    }
}
AndroidManifest.xml [permissions]

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