Turn ON and OFF bluetooth in Android with example


              Bluetooth is a communication protocol designed for short range, low bandwidth peer to peer communications. Using Android Bluetooth API's we can search, connect other Bluetooth devices within range. The local Bluetooth device is controlled via the BluetoothAdapter class, to access the default Bluetooth Adapter call getDefaultAdapter().
              In the below example lets see how to Turn ON and Turn OFF bluetooth in Android device. Create 3 buttons in your activity_main.xml to turn bluetooth ON, OFF and discoverable. 

TURN ON bluetooth:
      To enable bluetooth adapter you can start a system preference activity using the BluetoothAdapter.ACTION_REQUEST_ENABLE static constants as a startActivityForResult action string
startActivityForResult( new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);

Its prompts the user to turn on Bluetooth and asks for confirmation.

Make device discoverable :
          This can be achieved by starting a new activity using the  ACTION_REQUEST_DISCOVERABLE
startActivityForResult( new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);

By default discoverability will be enable for 2 minutes. You can modify the setting by adding EXTRA_DISCOVERABLE_DURATION extra to the launch Intent, specifying the number of seconds you want discoverability to last. 

Turn OFF bluetooth:
            Off bluetooth just by invoking the disable() function.
bluetooth.disable(); 

Permissions in Androidmanifest.xml
              To read any of the local blueooth adapter properties you need to include the Bluetooth permission in your application manifest.To modify any of the local device properties, the BLUETOOTH_ADMIN permission is also required.
<uses-permission android:name="android.permission.BLUETOOTH" />  
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 

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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/out"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
    </TextView>

    <Button
        android:id="@+id/turnON"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="49dp"
        android:text="TURN_ON" />

    <Button
        android:id="@+id/discoverable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="27dp"
        android:text="DISCOVERABLE" />

    <Button
        android:id="@+id/turnOFF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="28dp"
        android:text="TURN_OFF" />

</RelativeLayout>

Main_Activity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

  @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  final TextView out = (TextView) findViewById(R.id.out);
  final Button turnON = (Button) findViewById(R.id.turnON);
  final Button discoverable = (Button) findViewById(R.id.discoverable);
  final Button turnOFF = (Button) findViewById(R.id.turnOFF);
  final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

   turnON.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    if (!bluetooth.isEnabled()) {
     Toast.makeText(getApplicationContext(),
       "Turning ON Bluetooth", Toast.LENGTH_LONG);
     // Intent enableBtIntent = new
     // Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
     startActivityForResult(new Intent(
       BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
    }
   }
  });
  discoverable.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View arg0) {
    if (!bluetooth.isDiscovering()) {
     Toast.makeText(getApplicationContext(),
       "MAKING YOUR DEVICE DISCOVERABLE",
       Toast.LENGTH_LONG);
     // Intent enableBtIntent = new
     // Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
     startActivityForResult(new Intent(
       BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);

     }
   }
  });
  turnOFF.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View arg0) {
    bluetooth.disable();
    Toast.makeText(getApplicationContext(),
      "TURNING OFF BLUETOOTH", Toast.LENGTH_LONG);
   }
  });
 }

  @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidbluetooth"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidbluetooth.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Source code of this application:
AndroidBluetooth.zip



Reactions:

0 comments :

Post a Comment