Android bluetooth input device

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

Читайте также:  Android screen mirroring bluetooth

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) 

Источник

Android Bluetooth Paring Input Device

I am trying to make a pairing by code and it works only for normal devices. If I use a bluetooth scanner it pairs with it but the device doesn’t work till I go to android settings and select the Input Device checkbox. How can I do this by code? Thank you. Here is my pairing code:

public static BluetoothSocket createL2CAPBluetoothSocket(String address, int psm) < return createBluetoothSocket(TYPE_L2CAP, -1, false,false, address, psm); >// method for creating a bluetooth client socket private static BluetoothSocket createBluetoothSocket( int type, int fd, boolean auth, boolean encrypt, String address, int port) < try < Constructorconstructor = BluetoothSocket.class.getDeclaredConstructor( int.class, int.class,boolean.class,boolean.class,String.class, int.class); constructor.setAccessible(true); BluetoothSocket clientSocket = (BluetoothSocket) constructor.newInstance(type,fd,auth,encrypt,address,port); return clientSocket; >catch (Exception e) < return null; >> private void doPair(final BluetoothDevice device, final int deviceTag) < try < Method method = device.getClass().getMethod("createBond", (Class[]) null); method.invoke(device, (Object[]) null); >catch (Exception e) < Log.e(LOG_TAG, "Cannot pair device", e); >BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) < final int state = intent.getIntExtra( BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); final int prevState = intent.getIntExtra( BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) < Log.d(LOG_TAG, "Paired with new device"); if (listener != null) < listener.onBluetoothPairedDeviceChange(bluetoothAdapter .getBondedDevices().iterator().next() .getName(), deviceTag); >context.unregisterReceiver(this); > else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDING) < Log.d(LOG_TAG, "Cannot pair with new device"); if (listener != null) < listener.onBluetoothStatusChange(BluetoothHelper.IDLE_STATUS); >context.unregisterReceiver(this); > > > >; IntentFilter intent = new IntentFilter( BluetoothDevice.ACTION_BOND_STATE_CHANGED); context.registerReceiver(mReceiver, intent); > 

Источник

Читайте также:  All bluetooth devices software

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.

Источник

how to read from the InputStream of a bluetooth on Android

I am trying to test this bluetooth communication example between a PC and an Android phone. My SPP client is exactly the one from there and it works fine. I am new to Android and I didn’t want to make it run in a separate thread because I don’t know how, so I just did everything in the onCreate() method. If this is not the best way, feel free to point me to a better way, but this is not my main problem. The problem is I wanted to display the text received via bluetooth on a textView and I don’t know how to read from InputStream . When the code is left like that, it displays something like java.io.DataInputStream@41b0cb68 I tried it like here it didn’t display anything, also I don’t know what encoding is being used. here’s my android app’s code:

import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.app.Activity; import android.bluetooth.*; import android.util.Log; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends Activity < //based on java.util.UUID private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66"); // The local server socket private BluetoothServerSocket mmServerSocket; // based on android.bluetooth.BluetoothAdapter private BluetoothAdapter mAdapter; private BluetoothDevice remoteDevice; TextView text; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView) findViewById(R.id.textView_Text); BluetoothSocket socket = null; mAdapter = BluetoothAdapter.getDefaultAdapter(); // Listen to the server socket if we're not connected // while (true) < try < // Create a new listening server socket Log.d((String) this.getTitle(), ". Initializing RFCOMM SERVER. "); // MY_UUID is the UUID you want to use for communication mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService", MY_UUID); //mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try using In Secure connection. // This is a blocking call and will only return on a // successful connection or an exception socket = mmServerSocket.accept(); >catch (Exception e) < >try < Log.d((String) this.getTitle(), "Closing Server Socket. "); mmServerSocket.close(); InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); DataInputStream mmInStream = new DataInputStream(tmpIn); DataOutputStream mmOutStream = new DataOutputStream(tmpOut); // here you can use the Input Stream to take the string from the client whoever is connecting //similarly use the output stream to send the data to the client text.setText(mmInStream.toString()); >catch (Exception e) < //catch your exception here >// > > > 

I commented out the while(true) loop because I think it was making my app crash when onPause() was being called. I know this is not the best implementation but I really want to read from the bluetooth I feel like I am very close :), other aspects will be dealt with afterwards (like working with threads and so on).

Читайте также:  Пропадает связь через блютуз

Источник

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