Thursday, 21 March 2013

BlueTooth Turn On and Off

 The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.


Bluetooth Permission:
In order to use Bluetooth features in your application, you need to declare at least one of two
Bluetooth permissions: BLUETOOTH and BLUETOOTH_ADMIN.

You must request the BLUETOOTH permission in order to perform any Bluetooth communication, such
as requesting a connection, accepting a connection, and transferring data.

You must request the BLUETOOTH_ADMIN permission in order to initiate device discovery or
manipulate Bluetooth settings. Most applications need this permission solely for the ability to
discover local Bluetooth devices. The other abilities granted by this permission should not be
used, unless the application is a "power manager" that will modify Bluetooth settings upon user
request. Note: If you use BLUETOOTH_ADMIN permission, then must also have the BLUETOOTH
permission.


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

Setting Up Bluetooth:
Before your application can communicate over Bluetooth, you need to verify that Bluetooth is supported on the device, and if so, ensure that it is enabled.

If Bluetooth is not supported, then you should gracefully disable any Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the user enable Bluetooth without leaving your application. This setup is accomplished in two steps, using the BluetoothAdapter.




activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <CheckBox
        android:id="@+id/cboxEnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable"
        android:textSize="20dp"/>

</RelativeLayout>


MainActivity.java:
package com.ram.bt;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    BluetoothAdapter bluetoothAdapter;
    Integer REQ_BT_ENABLE = 1;
    CheckBox enable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
       
        enable = (CheckBox) findViewById(R.id.enableCheckBox);
       
        enable.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if (buttonView.isChecked()) {
                    if (bluetoothAdapter == null) {
                        Toast.makeText(getApplicationContext(),
                                "Device doesn't support Bluetooth",
                                Toast.LENGTH_LONG).show();
                    } else {
                        if (!bluetoothAdapter.isEnabled()) {   
                            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//implicit intent
                           
                            startActivityForResult(enableBtIntent,REQ_BT_ENABLE);
                           
                            Toast.makeText(getApplicationContext(),"Enabling Bluetooth....", Toast.LENGTH_LONG).show();
                        }
                    }
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Disabling Bluetooth....", Toast.LENGTH_LONG).show();
                    bluetoothAdapter.disable();
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == REQ_BT_ENABLE) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(getApplicationContext(),
                        "BlueTooth is now Enabled..", Toast.LENGTH_LONG).show();
            }
            if (resultCode == RESULT_CANCELED) {
                Toast.makeText(
                        getApplicationContext(),
                        "Error occured while enabling BlueTooth....",
                        Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}