Pair devices bluetooth android

How to pair with bluetooth device in android?

Hello Everyone I am working on Bluetooth and I want to pair my device with the finded bluetooth and connect with the paired bluetooth. I want to know how to do this. And I have also read about client server approach in which we use bluetoothserver socket and bluetooth socket and listenUsingRfcommWithServiceRecord and createRfcommSocketToServiceRecord methods in which we pass mac and uuid. I want to know where we use this approach and how to find the remote device UUId. Thanks in advance.

1 Answer 1

You don’t need to use the mentioned methods, at least for pairing the devices.

Try using Intents to pair. This code might let you get more familiar with Bluetooth.

 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); 

If you want a better approach on how to connect these paired devices, take a look at Bluetooth on AndroidDevelopers:

private class ConnectThread extends Thread < private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) < // Use a temporary object that is later assigned to mmSocket, // because mmSocket is final BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice try < // MY_UUID is the app's UUID string, also used by the server code tmp = device.createRfcommSocketToServiceRecord(MY_UUID); >catch (IOException e) < >mmSocket = tmp; > public void run() < // Cancel discovery because it will slow down the connection mBluetoothAdapter.cancelDiscovery(); try < // Connect the device through the socket. This will block // until it succeeds or throws an exception mmSocket.connect(); >catch (IOException connectException) < // Unable to connect; close the socket and get out try < mmSocket.close(); >catch (IOException closeException) < >return; > // Do work to manage the connection (in a separate thread) manageConnectedSocket(mmSocket); > /** Will cancel an in-progress connection, and close the socket */ public void cancel() < try < mmSocket.close(); >catch (IOException e) < >> > 

Источник

Читайте также:  Xiaomi sport bluetooth wireless earphone

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.

Читайте также:  Asus установить драйвер bluetooth

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.

Источник

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

Читайте также:  Блютуз модуль dualshock 4

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) 

Источник

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