Skip to main content
Among many ways, Bluetooth is a way to send or recieve data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
  1. Scan for other Bluetooth devices
  2. Get a list of paired devices
  3. Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);       
Apart from this constant , ther are other constanst provided the API , that supports differnet tasks. They are listed below.
Sr.NoConstant & description
1ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
2ACTION_STATE_CHANGED
This constant will notify that Bluetooth state has been changed
3ACTION_FOUND
This constant is used for recieving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the pariredDevices , there are other methods in the API that gives more control over Blueetooth. THey are listed below.
Sr.NoMethod & description
1enable()
This method enables the adapter if not enabled
2isEnabled()
This method returns true if adapter is enabled
3disable()
This method disables the adapter
4getName()
This method returns the name of the Bluetooth adapter
5setName(String name)
This method changes the Bluetooth name
6getState()
This method returns the current state of the Bluetooth Adapter.
7startDiscovery()
This method starts the discovery process of the Bluetooth for 120 seconds.

Example

This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list of paired devices by the Bluetooth.
To experiment with this example , you need to run this on an actual device.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as AudioCapture under a package com.example.audiocapture. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add the code 
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4Modify res/values/string.xml file and add necessary string components.
5Modify AndroidManifest.xml to add necessary permissions.
6Run the application and choose a running android device and install the application on it and verify the results.
Here is the content of src/com.example.bluetooth/MainActivity.java
package com.example.bluetooth;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private Button On,Off,Visible,list;
   private BluetoothAdapter BA;
   private Set<BluetoothDevice>pairedDevices;
   private ListView lv;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      On = (Button)findViewById(R.id.button1);
      Off = (Button)findViewById(R.id.button2);
      Visible = (Button)findViewById(R.id.button3);
      list = (Button)findViewById(R.id.button4);

      lv = (ListView)findViewById(R.id.listView1);

      BA = BluetoothAdapter.getDefaultAdapter();
   }

   public void on(View view){
      if (!BA.isEnabled()) {
         Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(turnOn, 0);
         Toast.makeText(getApplicationContext(),"Turned on" 
         ,Toast.LENGTH_LONG).show();
      }
      else{
         Toast.makeText(getApplicationContext(),"Already on",
         Toast.LENGTH_LONG).show();
         }
   }
   public void list(View view){
      pairedDevices = BA.getBondedDevices();

      ArrayList list = new ArrayList();
      for(BluetoothDevice bt : pairedDevices)
         list.add(bt.getName());

      Toast.makeText(getApplicationContext(),"Showing Paired Devices",
      Toast.LENGTH_SHORT).show();
      final ArrayAdapter adapter = new ArrayAdapter
      (this,android.R.layout.simple_list_item_1, list);
      lv.setAdapter(adapter);

   }
   public void off(View view){
      BA.disable();
      Toast.makeText(getApplicationContext(),"Turned off" ,
      Toast.LENGTH_LONG).show();
   }
   public void visible(View view){
      Intent getVisible = new Intent(BluetoothAdapter.
      ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible, 0);

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

}
Here is the content of 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" >

   <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentTop="true" >

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/app_name"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="on"
      android:text="@string/on" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="visible"
      android:text="@string/Visible" />

   <Button
      android:id="@+id/button3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="list"
      android:text="@string/List" />

   <Button
      android:id="@+id/button4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="off"
      android:text="@string/off" />

   <ListView
      android:id="@+id/listView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:visibility="visible" >

   </ListView>

   </LinearLayout>
</ScrollView>

</RelativeLayout>
Here is the content of Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Bluetooth</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="on">Turn On</string>
   <string name="off">Turn Off</string>
   <string name="Visible">Get Visible</string>
   <string name="List">List Devices</string>

</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.bluetooth"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <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.bluetooth.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>
Let's try to run your AndroidCapture application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Anroid Bluetooth Tutorial
Select your mobile device as an option and then check your mobile device which will display following screen:
Anroid Bluetooth Tutorial
Now select Turn On to turn on the bluetooth. But as you select it , your Bluetooth will not be turned on. Infact , it will ask your permission to enable the Bluetooth.
Anroid Bluetooth Tutorial
Now just select the Get Visible button to turn on your visibiltiy. The following screen would appear asking your permission to turn on discovery for 120 seconds.
Anroid Bluetooth Tutorial
Now just select the List Devices option. It will list down the paired devices in the list view. In my case , i have only one paired device. It is shown below.
Anroid Bluetooth Tutorial
Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you swithc off the bluetooth indicating the successfull swithching off of Bluetooth.
Anroid Bluetooth Tutorial

Comments

Popular posts from this blog

Android Tutorial

Android  is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a  linux-based Operating System ,  middleware  and  key mobile applications . It can be thought of as a mobile operating system. But it is not limited to mobile only. It is currently used in various devices such as mobiles, tablets, televisions etc. This tutorial is developed for beginners and experienced persons. Let's see the topics of android that we are going to learn. Basics of Android In this fundamental chapter, you will learn about android, its components, how to create first android application, internal of first android application etc. What is Android History and Version Software Stack Core Building Blocks Android Emulator Installing softwares Setup Eclipse Hello Android example Internal Details Dalvik VM AndroidManifest.xml R.java Hide Title Bar Activity and I...

CLOUD WORKFLOW SCHEDULING WITH DEADLINE AND TIME SLOT ALGORITHM

CLOUD WORKFLOW SCHEDULING WITH DEADLINE AND TIME SLOT ALGORITHM Abstract Allocating service capacities in cloud computing is based on the assumption that they are unlimited and can be used at any time. However, available service capacities change with workload and cannot satisfy users’ requests at any time from the cloud provider’s perspective because cloud services can be shared by multiple tasks. Cloud service providers provide available time slots for new user’s requests based on available capacities. In this paper, we consider workflow scheduling with deadline and time slot availability in cloud computing. An iterated heuristic framework is presented for the problem under study which mainly consists of initial solution construction, improvement, and perturbation. Three initial solution construction strategies, two greedy- and fair-based improvement strategies and a perturbation strategy are proposed. Different strategies in the three phases result in several heuristics. ...

MobiContext: A Context-aware Cloud-Based Venue Recommendation Framework

            MobiContext: A Context-aware Cloud-Based Venue Recommendation Framework ABSTRACT  In recent years, recommendation systems have seen significant evolution in the field of knowledge engineering. Most of the existing recommendation systems based their models on collaborative filtering approaches that make them simple to implement. However, performance of most of the existing collaborative filtering-based recommendation system suffers due to the challenges, such as: (a) cold start, (b) data sparseness, and (c) scalability. Moreover, recommendation problem is often characterized by the presence of many conflicting objectives or decision variables, such as users’ preferences and venue closeness. In this paper, we proposed MobiContext , a hybrid cloud-based Bi-Objective Recommendation Framework (BORF) for mobile social networks. The MobiContext utilizes multi-objective optimization techniques to generate personalized recommendat...