Android bluetooth pair code

Android Bluetooth Pairing without User Enter Pin and Confirmation Using Android API

I’m a beginner in Android programming since I only started 3 months ago. I’m doing a project which connects the android app to arduino using bluetooth. I already have a code for the android app (bluetooth.adapter,sockets,.etc.). The code for connection is already working. One of the goal is for the android app to automatically input the password when pairing with the bluetooth device without asking user to input the PIN. The old posts on this forum do not help much. (many suggested using insecure mode, but I do need secure mode, also in my case, the arduino is the server while cellphone app is the client, so the createInsecureRfcommSocketToServiceRecord() server method does not work for me) I searched and found this in android developer site about bluetoothdevice class: setPairingConfirmation(boolean confirm) Confirm passkey for PAIRING_VARIANT_PASSKEY_CONFIRMATION pairing. PAIRING_VARIANT_PIN = «The user will be prompted to enter a pin or an app will enter a pin for user». PAIRING_VARIANT_PASSKEY_CONFIRMATION = «The user will be prompted to confirm the passkey displayed on the screen or an app will confirm the passkey for the user» Seems using the code, the app will be the one to input the password and confirm the password making it an «auto-connect» features but the android site does not give a sample code on how to use this. Does any of you have a sample code in using this or related process? I appreciate your help!

3 Answers 3

First to clarify, this solution is designed for newer version of API (15 or later?)

I found the answer written in another post (see Roldofo’s answer in Here). Here is my reorganized answer with detailed code.

In a nutshell, you need to setup a broadcast receiver to trap the ACTION_PAIRING_REQUEST, and then programmatically pass the PIN and confirm.

Register a broadcast receiver:

 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST); getActivity().registerReceiver(mPairingRequestReceiver, filter); 

The definition of the receiver:

private final BroadcastReceiver mPairingRequestReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) < try < BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 1234); //the pin in case you need to accept for an specific pin Log.d(TAG, "Start Auto Pairing. PIN = " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",1234)); byte[] pinBytes; pinBytes = (""+pin).getBytes("UTF-8"); device.setPin(pinBytes); //setPairing confirmation if neeeded device.setPairingConfirmation(true); >catch (Exception e) < Log.e(TAG, "Error occurs when trying to auto pair"); e.printStackTrace(); >> > >; 

Then at your activity or fragment (wherever you want to initiate the pairing), you can call the following defined pairDevice() method to invoke pairing attempt (which will generate a ACTION_PAIRING_REQUEST)

private void pairDevice(BluetoothDevice device) < try < Log.d(TAG, "Start Pairing. with: " + device.getName()); device.createBond(); Log.d(TAG, "Pairing finished."); >catch (Exception e) < Log.e(TAG, e.getMessage()); >> 

Источник

Android + Pair devices via bluetooth programmatically

I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair. I want to know mistake in my code or any other way to do what i need.

package com.marakana; import java.util.Set; 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.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class BluetoothDemo extends Activity < // Debugging private static final String TAG = "DeviceListActivity"; private static final boolean D = true; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdaptermPairedDevicesArrayAdapter; private ArrayAdapter mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener() < public void onClick(View v) < doDiscovery(); v.setVisibility(View.GONE); >>); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) < findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) < mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> else < String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); >> @Override protected void onDestroy() < super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) < mBtAdapter.cancelDiscovery(); >// Unregister broadcast listeners this.unregisterReceiver(mReceiver); > /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() < if (D) Log.d(TAG, "doDiscovery()"); // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) < mBtAdapter.cancelDiscovery(); >// Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); > // The on-click listener for all devices in the ListViews private OnItemClickListener mDeviceClickListener = new OnItemClickListener() < public void onItemClick(AdapterViewav, View v, int arg2, long arg3) < // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); >>; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) < mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >// When discovery is finished, change the Activity title > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) < String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); >> > >; > 

Источник

Читайте также:  Which ipods have bluetooth

How to pair Bluetooth device programmatically Android

I am developing an application where I want to connect a Bluetooth device main issue is I don’t want user to enter required pin instead application should do that by himself. I don’t have any connection related issue. Only want to insert and complete pin authentication process by application itself. I found following code I am sure it is working but not sure on how to add pin in this code??

private void pairDevice(BluetoothDevice device) < try < Log.d("pairDevice()", "Start Pairing. "); Method m = device.getClass().getMethod("createBond", (Class[]) null); m.invoke(device, (Object[]) null); Log.d("pairDevice()", "Pairing finished."); >catch (Exception e) < Log.e("pairDevice()", e.getMessage()); >> 

8 Answers 8

This seems to give you the answer, with the pin entering and all. It involves sending .setPin() whenever you get the message.

So, I had this question, if someone needs the answer to this working in android 4.4.2.

 IntentFilter filter = new IntentFilter( "android.bluetooth.device.action.PAIRING_REQUEST"); /* * Registering a new BTBroadcast receiver from the Main Activity context * with pairing request event */ registerReceiver( new PairingRequest(), filter); 

And the code for the Receiver.

 public static class PairingRequest extends BroadcastReceiver < public PairingRequest() < super(); >@Override public void onReceive(Context context, Intent intent) < if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) < try < BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0); //the pin in case you need to accept for an specific pin Log.d("PIN", " " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0)); //maybe you look for a name or address Log.d("Bonded", device.getName()); byte[] pinBytes; pinBytes = (""+pin).getBytes("UTF-8"); device.setPin(pinBytes); //setPairing confirmation if neeeded device.setPairingConfirmation(true); >catch (Exception e) < e.printStackTrace(); >> > > 

And the broadcastReceiver.

No, I dont think so this solution was for android 4.4.2 and android 5, not sure about android 6 and up. @TejasPandya

Читайте также:  Айфон блютуз виден всем

Does this solution work without Bluetooth_Priveldge permission? Doesn’t this device.setPairingConfirmation(true); line need the permisiion mentioned above to work ?

@Harrish it should work, but it will depend on the device, some devices require pairing confirmation sent, and some assume that once you are connected you are paired, also this solution was for android 4.4.2 and android 5, so you should probably do something similar for android 6 and above.

The method setPairingConfirmation needs the BLUETOOTH_PRIVILEDGED permission which is not available to third party apps. But with abortBroadcast it’s working on my Pixel 4 XL!

How to set the pin code has been answered above (and that helped me). Yet, I share my simple code below which works with Android 6:

BluetoothAdapter mBTA = BluetoothAdapter.getDefaultAdapter(); if (mBTA.isDiscovering()) mBTA.cancelDiscovery(); mBTA.startDiscovery(); . /** In a broadcast receiver: */ if (BluetoothDevice.ACTION_FOUND.equals(action)) < // One device found. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d(TAG, "Start Pairing. with: " + device.getName()); device.createBond(); >// If you want to auto-input the pin#: else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
public void pairDevice(BluetoothDevice device) < String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST"; Intent intent = new Intent(ACTION_PAIRING_REQUEST); String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE"; intent.putExtra(EXTRA_DEVICE, device); String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT"; int PAIRING_VARIANT_PIN = 0; intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); >Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST); intent.putExtra(EXTRA_DEVICE, device); int PAIRING_VARIANT_PIN = 272; intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN); sendBroadcast(intent); Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); startActivityForResult(intent, REQUEST_PAIR_DEVICE); 

Please help me. I want list of device that has BT enabled and after click on particular bluetooth device, it is paired with our device

Register a BluetoothDevice.ACTION_PAIRING_REQUEST receiver onCreate()

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST) registerReceiver(pairingReceiver, pairingRequestFilter) 

on receiver set your pin using setPin() and call abortBroadcast()

val PAIRING_PIN=1234 private var pairingReceiver = object : BroadcastReceiver() < override fun onReceive(context: Context?, intent: Intent?) < val action = intent. action if (BluetoothDevice.ACTION_PAIRING_REQUEST == action) < val device: BluetoothDevice? =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) val type =intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR) if (type == BluetoothDevice.PAIRING_VARIANT_PIN) < device?.setPin(PAIRING_PIN.toByteArray()) abortBroadcast() >> > > 

Don’t forget to unregister receiver on onDestroy()

Читайте также:  Передача экрана через блютуз

if it doesn’t work for you, try setting hight priority to receiver

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST) pairingRequestFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY - 1 registerReceiver(pairingReceiver, pairingRequestFilter) 

Also you can register a receiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED to read status of pairing

val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED) registerReceiver(receiver, filter) 

Источник

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.

Источник

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