Android Bluetooth Code Example

Android Bluetooth Tutorial

Android Bluetooth is ways to send or acquire data between two different devices. Android system includes support for the Android Bluetooth framework which allows a tool to wireless exchange data with other Bluetooth devices.

Android OS facilitates Android Bluetooth API to execute these different businesses.

  • Check for other Bluetooth devices
  • Get a set of paired devices
  • Hook up to other devices through service discovery

Google android provides Android Bluetooth Adapter class to talk to Bluetooth. Create an subject of this getting in touch with by getting in touch with the static method getDefaultAdapter(). Its syntax is listed below.

private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

To be able to permit the Bluetooth of your device, call the purpose with the next Bluetooth regular ACTION_Submission_ENABLE. Its code is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);       

 

From this continuous apart, there are other constants provided the android  bluetooth API , that helps different tasks. They below are listed.

Regular & description

ACTION_REQUEST_DISCOVERABLE

This continuous can be used for start obtaining of bluetooth

ACTION_STATE_CHANGED

This regular will inform that Android Bluetooth status has been changed

ACTION_FOUND

This continuous is employed for acquiring information about each device that is discovered

Once the Bluetooth is enabled by you , you can get a set of combined devices by dialling getBondedDevices() method. A place is came back because of it of bluetooth devices. Its code is.

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

 

Form the parried Devices aside , there are other methods in the API that provides more control over Android Blueetooth. They are really listed below.

Methods & Descriptions

enable()

The adapter is enabled by this method if not enabled

isEnabled()

This method results true if adapter is enabled

disable()

This technique disables the Android Bluetooth adapter

getName()

This technique comes back the name of the Android Bluetooth adapter

setName(String name)

The Bluetooth is altered by this technique name

getState()

This method comes back the current status of the Android Bluetooth Adapter.

startDiscovery()

This technique begins the breakthrough procedure for the Bluetooth for 120 secs.

Android Bluetooth Example

This android Bluetooth example provides demo of android Bluetooth Adapter class to control Bluetooth and show set of combined devices by the Bluetooth.

To test out this android bluetooth example , you will need to perform this on a genuine device.

Steps     Description

  1. You use Android studio to generate an Android software a program com.example.sappal.myapplication;. While creating this job, ensure you Goal SDK and Compile With at the latest version of Android os SDK to make use of higher degrees of APIs.
  2. Modify src/MainActivity.java to include the all syntax and code
  3. Modify design XML  res/design/activity_main.xml add any GUI element if required.
  4. Modify AndroidManifest.xml to include necessary permissions.
  5. Run the application form and choose a working android os device and mount the application onto it and check the results.

This is actually the content of src/MainActivity.java

package com.example.sappal.myapplication;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends Activity  {
   Button b1,b2,b3,b4;
   private BluetoothAdapter BA;
   private Set<BluetoothDevice>pairedDevices;
   ListView lv;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1 = (Button) findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      b3=(Button)findViewById(R.id.button3);
      b4=(Button)findViewById(R.id.button4);
      
      BA = BluetoothAdapter.getDefaultAdapter();
      lv = (ListView)findViewById(R.id.listView);
   }
   
   public void on(View v){
      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 off(View v){
      BA.disable();
      Toast.makeText(getApplicationContext(),"Turned off" ,Toast.LENGTH_LONG).show();
   }
   
   public  void visible(View v){
      Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible, 0);
   }
   
   public void list(View v){
      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);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="Bluetooth Example" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Andro Development"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Turn On"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_toStartOf="@+id/imageView"
      android:layout_toLeftOf="@+id/imageView"
      android:clickable="true"
      android:onClick="on" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Get visible"
      android:onClick="visible"
      android:id="@+id/button2"
      android:layout_alignBottom="@+id/button"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="List devices"
      android:onClick="list"
      android:id="@+id/button3"
      android:layout_below="@+id/imageView"
      android:layout_toRightOf="@+id/imageView"
      android:layout_toEndOf="@+id/imageView" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="turn off"
      android:onClick="off"
      android:id="@+id/button4"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <ListView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/listView"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/button"
      android:layout_alignStart="@+id/button"
      android:layout_below="@+id/textView2" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Paired devices:"
      android:id="@+id/textView2"
      android:textColor="#ff34ff06"
      android:textSize="25dp"
      android:layout_below="@+id/button4"
      android:layout_alignLeft="@+id/listView"
      android:layout_alignStart="@+id/listView" />

</RelativeLayout>

Here is the content of Strings.xml

<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</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.sappal.myapplication" >
   <uses-permission android:name="android.permission.BLUETOOTH"/>
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".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 make an effort to run the application. I suppose you have linked your actual Google android Mobile device with your personal computer. To perform the app from Android studio room, available one of your project’s activity documents and click Run Eclipse Run Icon from the tool. Before starting the application, Android studio room will display pursuing window to choose a choice where you want to perform your Android software.

android bluetooth

Now choose START to carefully turn on the bluetooth. But as you decide on it , your Bluetooth shall not be fired up. In fact , it will ask your permission to permit the Bluetooth.

android bluetooth

Now choose the Get Visible  button to carefully turn on your presence just. The next screen seems asking your permission to carefully turn on discovery for 120 seconds.

android bluetooth

Now just choose the List Devices option. It shall list down the combined devices in the list view. In my own case , I’ve only 1 paired device. It really is shown below.

android bluetooth

Now just choose the Switch off button to change off of the Bluetooth. Following message seems when you turn off the bluetooth indicating the successful switching from Bluetooth.

android-bluetooth