AdSense

AdSense3

Tuesday 27 October 2015

Android Bluetooth

Bluetooth is a way to exchange data with other devices wirelessly. Android provides Bluetooth API to perform several tasks such as:

  • scan bluetooth devices
  • Connect and transfer data from and to other devices
  • manage multiple connections etc.

Android Bluetooth API

The android.bluetooth package provides a lot of interfaces classes to work with bluetooth such as:
  • BluetoothAdapter
  • BluetoothDevice
  • BluetoothSocket
  • BluetoothServerSocket
  • BluetoothClass
  • BluetoothProfile
  • BluetoothProfile.ServiceListener
  • BluetoothHeadset
  • BluetoothA2dp
  • BluetoothHealth
  • BluetoothHealthCallback
  • BluetoothHealthAppConfiguration

BluetoothAdapter class

By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate device discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for connection requests etc.

Constants of BluetoothAdapter class

BluetoothAdapter class provides many constants. Some of them are as follows:
  • String ACTION_REQUEST_ENABLE
  • String ACTION_REQUEST_DISCOVERABLE
  • String ACTION_DISCOVERY_STARTED
  • String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Commonly used methods of BluetoothAdapter class are as follows:
  • static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of BluetoothAdapter.
  • boolean enable() enables the bluetooth adapter if it is disabled.
  • boolean isEnabled() returns true if the bluetooth adapter is enabled.
  • boolean disable() disables the bluetooth adapter if it is enabled.
  • String getName() returns the name of the bluetooth adapter.
  • boolean setName(String name) changes the bluetooth name.
  • int getState() returns the current state of the local bluetooth adapter.
  • Set<BluetoothDevice> getBondedDevices() returns a set of paired bonded) BluetoothDevice objects.
  • boolean startDiscovery() starts the discovery process.

Android Bluetooth Example: enable, disable and make discovrable bluetooth programmatically

You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <TextView android:text=""  
  8.      android:id="@+id/out"   
  9.      android:layout_width="wrap_content"   
  10.      android:layout_height="wrap_content">  
  11.     </TextView>  
  12.     <Button  
  13.         android:id="@+id/button1"  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:layout_alignParentLeft="true"  
  17.         android:layout_alignParentTop="true"  
  18.         android:layout_marginLeft="30dp"  
  19.         android:layout_marginTop="49dp"  
  20.         android:text="TURN_ON" />  
  21.   
  22.     <Button  
  23.         android:id="@+id/button2"  
  24.         android:layout_width="wrap_content"  
  25.         android:layout_height="wrap_content"  
  26.         android:layout_alignLeft="@+id/button1"  
  27.         android:layout_below="@+id/button1"  
  28.         android:layout_marginTop="27dp"  
  29.         android:text="DISCOVERABLE" />  
  30.   
  31.     <Button  
  32.         android:id="@+id/button3"  
  33.         android:layout_width="wrap_content"  
  34.         android:layout_height="wrap_content"  
  35.         android:layout_alignLeft="@+id/button2"  
  36.         android:layout_below="@+id/button2"  
  37.         android:layout_marginTop="28dp"  
  38.         android:text="TURN_OFF" />  
  39.   
  40. </RelativeLayout>  

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.
  1. <uses-permission android:name="android.permission.BLUETOOTH" />  
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  
The full code of AndroidManifest.xml file is given below.
File: AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.bluetooth"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="16" />  
  10.   
  11.     <uses-permission android:name="android.permission.BLUETOOTH" />  
  12.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  
  13.   
  14.     <application  
  15.         android:allowBackup="true"  
  16.         android:icon="@drawable/ic_launcher"  
  17.         android:label="@string/app_name"  
  18.         android:theme="@style/AppTheme" >  
  19.         <activity  
  20.             android:name="com.example.bluetooth.MainActivity"  
  21.             android:label="@string/app_name" >  
  22.             <intent-filter>  
  23.                 <action android:name="android.intent.action.MAIN" />  
  24.   
  25.                 <category android:name="android.intent.category.LAUNCHER" />  
  26.             </intent-filter>  
  27.         </activity>  
  28.     </application>  
  29.   
  30. </manifest>  

Activity class

Let's write the code to enable, disable and make bluetooth discoverable.
File: MainActivity.java
  1. package com.example.bluetooth;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.view.Menu;  
  5. import android.app.Activity;  
  6. import android.bluetooth.BluetoothAdapter;  
  7. import android.content.Context;  
  8. import android.content.Intent;  
  9. import android.os.Bundle;  
  10. import android.util.Log;  
  11. import android.view.View;  
  12. import android.widget.Button;  
  13. import android.widget.TextView;  
  14. import android.widget.Toast;  
  15.   
  16. public class MainActivity extends Activity {  
  17.       private static final int REQUEST_ENABLE_BT = 0;  
  18.       private static final int REQUEST_DISCOVERABLE_BT = 0;  
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.     final TextView out=(TextView)findViewById(R.id.out);  
  24.     final Button button1 = (Button) findViewById(R.id.button1);  
  25.     final Button button2 = (Button) findViewById(R.id.button2);  
  26.     final Button button3 = (Button) findViewById(R.id.button3);  
  27.     final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
  28.     if (mBluetoothAdapter == null) {  
  29.        out.append("device not supported");  
  30.     }  
  31.     button1.setOnClickListener(new View.OnClickListener() {  
  32.         public void onClick(View v) {  
  33.             if (!mBluetoothAdapter.isEnabled()) {  
  34.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  35.                 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);  
  36.             }  
  37.         }  
  38.     });  
  39.     button2.setOnClickListener(new View.OnClickListener() {  
  40.      @Override  
  41.         public void onClick(View arg0) {  
  42.             if (!mBluetoothAdapter.isDiscovering()) {  
  43.                   //out.append("MAKING YOUR DEVICE DISCOVERABLE");  
  44.                    Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE",  
  45.              Toast.LENGTH_LONG);  
  46.   
  47.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  48.                 startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);  
  49.                     
  50.             }  
  51.         }  
  52.     });  
  53.     button3.setOnClickListener(new View.OnClickListener() {  
  54.         @Override  
  55.         public void onClick(View arg0) {     
  56.             mBluetoothAdapter.disable();  
  57.             //out.append("TURN_OFF BLUETOOTH");  
  58.             Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_LONG);  
  59.            
  60.             }  
  61.     });  
  62. }  
  63.   
  64.     @Override  
  65.     public boolean onCreateOptionsMenu(Menu menu) {  
  66.         // Inflate the menu; this adds items to the action bar if it is present.  
  67.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  68.         return true;  
  69.     }  
  70.   
  71. }  

You need to run it on the real device (e.g. mobile) to test the application.

No comments:

Post a Comment