Code android bluetooth connection

How to programmatically pair a bluetooth device on Android

For my application I’m trying to programmatically pair a bluetooth device. I’m able to show the pairing dialog for the device I want to pair and I can enter a pincode. When I press «Pair» the dialog is removed and nothing happens. I only need to support devices with Android 2.0 and newer. Currently I am using the following code to start the pairing progress:

 public void pairDevice(BluetoothDevice device)

i spent several days looking for a solution to this exact issue. it appears that google considers force-pairing to be a security issue, so the ACTION types you have listed here don’t actually exist. i found the class you reference here: developer.oesf.biz/em/developer/reference/cinnamon/android/… but it’s not in the official docs: developer.android.com/reference/android/bluetooth/…

Using reflection you can call the method createBond from the BluetoothDevice class. Solution: See this post: How to unpair or delete paired bluetooth device programmatically on android(stackoverflow.com/questions/9608140/…)? There is also a solution for unpair.

10 Answers 10

I managed to auto request a pairing procedure with keyboard featured devices through an app working as a service checking the presence of a specific kind of device and a modified version of the Settings app.

I have to say that I was working on a custom device running Android 4.0.3 without external controls (no back/Home/confirm buttons): pairing a controller on boot complete without any interaction until PIN request was mandatory.

First I created a service starting an activity on boot (with android.intent.action.BOOT_COMPLETED and android.permission.RECEIVE_BOOT_COMPLETED) that checks periodically the presence of a 1344 class device (a keyboard, the only way to input data on request) on the onReceive callback:

public void onReceive(Context context, Intent intent) . BluetoothDevice dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); . if(dev.getBluetoothClass().getDeviceClass() == 1344)

Once filtered I choose the first keyboard available and then I pass the BT address to the Settings app:

Intent btSettingsIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); btSettingsIntent.putExtra("btcontroller", dev.getAddress()); startActivityForResult(btSettingsIntent, 1); 

The tricky part was looking for the best position to call the pairing process. Using only the

intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN); 

led me to a paring dialog that once closed left me with the device paired, but unusable.

Digging into the classes of com.Android.settings.Bluetooth I found my way through the

createDevicePreference(CachedBluetoothDevice cachedDevice) 

in the DeviceListPreferenceFragment.

From there I did compare my previously selected BT address with those available coming up and once successfully matched I call

I know, it’s tricky and requires access to the Android source code, but in a custom environment it works.

I hope this could be helpful.

Источник

Android — Bluetooth Connection Demo

Bluetooth:The Android platform supports Bluetooth connection, which allows exchanging data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs connect to other Bluetooth devices.

Читайте также:  Блютуз колонка сони экстра басс

All of the Bluetooth APIs is available in the Android Bluetooth package.

Here is a summary of the classes you will need to create as below:

BluetoothAdapter Represents the local Bluetooth adapter (Bluetooth radio).
BluetoothDevice Represents a remote Bluetooth device, query information such as its name, address, class, and bonding state.
BluetoothSocket Represents the interface for a Bluetooth socket (similar to a TCP Socket).
BluetoothServerSocket Represents an open server socket that listens for incoming requests (similar to a TCP ServerSocket).
BluetoothClass Describes the general characteristics and capabilities of a Bluetooth device.

In our example we are going to create an application which get the information about the Bluetooth connections is activates and deactivates Bluetooth.

Step 1 Check Bluetooth Connection

First we need check Bluetooth connection. So Create new class named Connections.

public class Connections < private static boolean state = false; public static boolean blueTooth() < BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if (!bluetooth.isEnabled()) < System.out.println("Bluetooth is Disable. "); state = true; >else if (bluetooth.isEnabled()) < String address = bluetooth.getAddress(); String name = bluetooth.getName(); System.out.println(name + " : " + address); state = false; >return state; > >

Step 2 MainActivity.java file

Now when we got the response from the Connections class in our Main Activity with BT in Off state we get dialog for On BT.

Then we create new method into main activity class for the setting up all the Bluetooth information into Text View.

public class MainActivity extends Activity < private static final int REQUEST_ENABLE_BT = 12; private TextView out; private BluetoothAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); out = (TextView) findViewById(R.id.tvBluetoothInfo); setBluetoothData(); if (Connections.blueTooth()) < Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); >> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); out.setText(""); setBluetoothData(); >private void setBluetoothData() < // Getting the Bluetooth adapter adapter = BluetoothAdapter.getDefaultAdapter(); out.append("\nAdapter: " + adapter.toString() + "\n\nName: " + adapter.getName() + "\nAddress: " + adapter.getAddress()); // Check for Bluetooth support in the first place // Emulator doesn't support Bluetooth and will return null if (adapter == null) < Toast.makeText(this, "Bluetooth NOT supported. Aborting.", Toast.LENGTH_LONG).show(); >// Starting the device discovery out.append("\n\nStarting discovery. "); adapter.startDiscovery(); out.append("\nDone with discovery. \n"); // Listing paired devices out.append("\nDevices Pared:"); Set devices = adapter.getBondedDevices(); for (BluetoothDevice device : devices) < out.append("\nFound device: " + device.getName() + " Add: " + device.getAddress()); >> >

For More Details visit following links:

I hope you enjoy this tutorial and it would be helpful to you.

Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in India.

Tejas Jasani

An entrepreneur who has founded 2 flourishing software firms in 7 years, Tejas is keen to understand everything about gaming — from the business dynamics to awesome designs to gamer psychology. As the founder-CEO of a company that has released some very successful games, he knows a thing or two about gaming. He shares his knowledge through blogs and talks that he gets invited to.

Читайте также:  Как правильно заряжать беспроводные наушники bluetooth

Источник

Android Bluetooth with Examples

In android, Bluetooth is a communication network protocol, which allows devices to connect wirelessly to exchange the data with other Bluetooth devices.

Generally, in android applications by using Bluetooth API’s we can implement Bluetooth functionalities, such as searching for the available Bluetooth devices, connecting with the devices and managing the data transfer between devices within the range.

By using android Bluetooth API’s in android applications, we can perform the following functionalities.

  • Scan for the available Bluetooth devices within the range
  • Use local Bluetooth adapter for paired Bluetooth devices
  • Connect to other devices through service discovery
  • Transfer data to and from other devices
  • Manage multiple connections

To transfer the data between two Bluetooth devices first, they must establish a communication channel using the pairing process. The devices which we are going to pair must be discoverable and should accept the incoming connection requests. Generally, the devices will find discoverable devices using a service discovery process. Once the device accepts the pairing request, the two devices will exchange security keys to complete the bonding process and the devices will cache these security keys for later use.

Once the pairing and bonding process completes, the devices are ready to exchange the required information. When the session is complete, the device that initiated the pairing request will release the channel that linked to the discoverable device. The two devices remain bonded, so they can reconnect automatically during a future session as long as they’re in the range of each other.

Android Set Bluetooth Permissions

To use Bluetooth features in our android applications, we must need to add multiple permissions, such as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in our manifest file.

Permission Description
BLUETOOTH We need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.
LOCATION We need this permission because the Bluetooth scans can be used to gather the information about the location of user.

In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings from our app, we need to define BLUETOOTH_ADMIN permission.

Following is the example of defining the Bluetooth permissions in android manifest file.

Android BluetoothAdapter Class

In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our applications.

By using BluetoothAdapter object, we can interact with device’s Bluetooth adapter to perform Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it will return null.

Following is the code snippet to initialize BluetoothAdapter class and to know whether the Bluetooth is supported on the device or not.

Читайте также:  Блютуз колонка свен 370

BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
if (bAdapter== null )
// Device won’t support Bluetooth
>

If you observe above code snippet, we used the getDefaultAdapter() method of BluetoothAdapter class, which will return whether the device contains Bluetooth adapter or not.

In case if getDefaultAdapter() method returns NULL, then the device does not support Bluetooth and we can disable all Bluetooth features.

Android Enable or Disable Bluetooth

If Bluetooth is supported but disabled, then the isEnabled() method will return false and we can request the user to enable Bluetooth without leaving our application by using startActivityForResult() method with ACTION_REQUEST_ENABLE intent action parameter.

Following is the code snippet to enable a Bluetooth by using BluetoothAdapter parameter ACTION_REQUEST_ENABLE.

if (!bAdapter.isEnabled())
Intent eintent = new Intent(BluetoothAdapter. ACTION_REQUEST_ENABLE );
startActivityForResult(eintent, intVal);
>

If you observe above code snippet, we used startActivityForResult() method with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth.

The second parameter intVal in startActivityForResult() method is a locally defined integer that must be greater than 0 and the system will return this parameter back to us during onActivityResult() implementation as a requestCode parameter.

To know more about to TURN ON / OFF Bluetooth in android applications, check this Android Bluetooth Turn ON / OFF with Examples.

Android Enable Discoverability

To make the device discoverable to other devices, we need to start the new activity by calling startActivityForResult(intent, int) with the ACTION_REQUEST_DISCOVERABLE intent.

Following is the code snippet to enable the system’s discoverable mode to make sure that the device discoverable to other devices.

Intent dIntent = new Intent(BluetoothAdapter. ACTION_REQUEST_DISCOVERABLE );
dIntent.putExtra(BluetoothAdapter. EXTRA_DISCOVERABLE_DURATION , 300 );
startActivity(dIntent);

If you observe above code snippet, we are making sure our device discoverable to other devices using ACTION_REQUEST_DISCOVERABLE. By default, the device becomes discoverable for 120 seconds. We can extend the device discoverable duration up to 3600 seconds (1 hour), by adding the EXTRA_DISCOVERABLE_DURATION extra.

To know more about device discoverability, check this Android Bluetooth Device Discoverability with Examples.

Android List Paired Devices

By using the BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired devices list.

Following is the code snippet to get all paired devices with name and MAC address of each device.

// Get paired devices.
Set pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0 ) // There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
>
>

If you observe above code, we are getting the Bluetooth paired devices name and mac address by using BluetoothDevice object.

To know more about Bluetooth pair devices, check this Android Bluetooth List Pair Devices with Examples.

This is how we can use Bluetooth in android applications to allow a devices to connect wirelessly to exchange the data with other Bluetooth devices.

Источник

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