Bluetooth tutorial in android

Bluetooth overview

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

Using the Bluetooth APIs, an app can perform the following:

  • Scan for other Bluetooth devices.
  • Query the local Bluetooth adapter for paired Bluetooth devices.
  • Establish RFCOMM channels.
  • Connect to other devices through service discovery.
  • Transfer data to and from other devices.
  • Manage multiple connections.

This topic focuses on Classic Bluetooth. Classic Bluetooth is the right choice for more battery-intensive operations, which include streaming and communicating between devices. For Bluetooth devices with low power requirements, consider using Bluetooth Low Energy connections.

This documentation describes different Bluetooth profiles and explains how to use the Bluetooth APIs to accomplish the four major tasks necessary to communicate using Bluetooth:

  • Setting up Bluetooth.
  • Finding devices that are either paired or available in the local area.
  • Connecting devices.
  • Transferring data between devices.

For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

The basics

For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of communication using a pairing process. One device, a discoverable device, makes itself available for incoming connection requests. Another device finds the discoverable device using a service discovery process. After the discoverable device accepts the pairing request, the two devices complete a bonding process in which they exchange security keys. The devices cache these keys for later use. After the pairing and bonding processes are complete, the two devices exchange information. When the session is complete, the device that initiated the pairing request releases the channel that had linked it to the discoverable device. The two devices remain bonded, however, so they can reconnect automatically during a future session as long as they’re in range of each other and neither device has removed the bond.

Use of the Bluetooth APIs requires declaring several permissions in your manifest file. Once your app has permission to use Bluetooth, your app needs to access the BluetoothAdapter and determine if Bluetooth is available on the device. If Bluetooth is available, there are three steps to make a connection:

Читайте также:  Ps4 gamepad bluetooth pin code

Certain devices use a specific Bluetooth profile that declares the data it provides.

Key classes and interfaces

All of the Bluetooth APIs are available in the android.bluetooth package. The following are the classes and interfaces you need in order to create Bluetooth connections:

BluetoothAdapter Represents the local Bluetooth adapter (Bluetooth radio). The BluetoothAdapter is the entry-point for all Bluetooth interaction. Using this, you can discover other Bluetooth devices, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for communications from other devices. BluetoothDevice Represents a remote Bluetooth device. Use this to request a connection with a remote device through a BluetoothSocket or query information about the device such as its name, address, class, and bonding state. BluetoothSocket Represents the interface for a Bluetooth socket (similar to a TCP Socket ). This is the connection point that allows an app to exchange data with another Bluetooth device using InputStream and OutputStream . BluetoothServerSocket Represents an open server socket that listens for incoming requests (similar to a TCP ServerSocket ). In order to connect two devices, one device must open a server socket with this class. When a remote Bluetooth device makes a connection request to this device, the device accepts the connection and then returns a connected BluetoothSocket . BluetoothClass Describes the general characteristics and capabilities of a Bluetooth device. This is a read-only set of properties that defines the device’s classes and services. Although this information provides a useful hint regarding a device’s type, the attributes of this class don’t necessarily describe all Bluetooth profiles and services that the device supports. BluetoothProfile An interface that represents a Bluetooth profile. A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices. An example is the Hands-Free profile. For more discussion of profiles, see Bluetooth profiles. BluetoothHeadset Provides support for Bluetooth headsets to be used with mobile phones. This includes both the Bluetooth Headset profile and the Hands-Free (v1.5) profile. BluetoothA2dp Defines how high-quality audio can be streamed from one device to another over a Bluetooth connection using the Advanced Audio Distribution Profile (A2DP). BluetoothHealth Represents a Health Device Profile proxy that controls the Bluetooth service. BluetoothHealthCallback An abstract class that you use to implement BluetoothHealth callbacks. You must extend this class and implement the callback methods to receive updates about changes in the app’s registration state and Bluetooth channel state. BluetoothHealthAppConfiguration Represents an app configuration that the Bluetooth Health third-party app registers to communicate with a remote Bluetooth health device. BluetoothProfile.ServiceListener An interface that notifies BluetoothProfile interprocess communication (IPC) clients when they have been connected to or disconnected from the internal service that runs a particular profile.

Читайте также:  Пропадает значок bluetooth windows 10

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2021-10-27 UTC.

Источник

Android — Bluetooth

Among many ways, Bluetooth is a way to send or receive 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.

  • Scan for other Bluetooth devices
  • Get a list of paired devices
  • 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, there are other constants provided the API , that supports different tasks. They are listed below.

ACTION_REQUEST_DISCOVERABLE

This constant is used for turn on discovering of bluetooth

This constant will notify that Bluetooth state has been changed

This constant is used for receiving 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 SetpairedDevices; pairedDevices = BA.getBondedDevices();

Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth. They are listed below.

This method enables the adapter if not enabled

This method returns true if adapter is enabled

This method disables the adapter

This method returns the name of the Bluetooth adapter

This method changes the Bluetooth name

This method returns the current state of the Bluetooth Adapter.

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.

Steps Description
1 You will use Android studio to create an Android application a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add the code
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4 Modify AndroidManifest.xml to add necessary permissions.
5 Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/MainActivity.java

package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Set; public class MainActivity extends Activity < Button b1,b2,b3,b4; private BluetoothAdapter BA; private SetpairedDevices; 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); >>

Here is the content of activity_main.xml

Here is the content of Strings.xml

Here is the content of AndroidManifest.xml

Eclipse Run Icon

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the tool bar.If your Bluetooth will not be turned on then, it will ask your permission to enable the Bluetooth.

Anroid Bluetooth Tutorial

Now just select the Get Visible button to turn on your visibility. 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 switch off the bluetooth indicating the successful switching off of Bluetooth.

Источник

Оцените статью
Adblock
detector