Connect to bluetooth device android code

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.

Источник

Connect to specific bluetooth device android code example

So you need or to add scanning screen where user will be able to choose needed devices or to hardcode one of the devices parameters. For example you can save already connected devices to list to avoid reconnection and so forth You can read more here: https://medium.com/@avigezerit/bluetooth-low-energy-on-android-22bc7310387a Solution: If you know the name of the device you wish to pair to you can use an equals comparison.

Читайте также:  Можно ли прошить блютуз колонку

Connecting with a specific bluetooth device

I did not quite understand the whole point of your application, but in any case, to connect to any particular device, you need to know either its name or the mac address or a specific service or characteristic. So you need or to add scanning screen where user will be able to choose needed devices or to hardcode one of the devices parameters. And when you will have list of needed devices you can scan for them.

Then connect to device and disconnect after specific time. All other staff you can implement according to your needed. For example you can save already connected devices to list to avoid reconnection and so forth

You can read more here: https://medium.com/@avigezerit/bluetooth-low-energy-on-android-22bc7310387a

Bluetooth profiles | Android Developers, A Bluetooth profile is a wireless interface specification for Bluetooth-based communication between devices, such as the Hands-Free profile. For a mobile device to connect to a wireless headset, both devices must support the Hands-Free profile. The Bluetooth API provides implementations for the …

Connect to a specific bluetooth paired device

If you know the name of the device you wish to pair to you can use an equals comparison.

private static final String DEVICE_WE_WANT_TO MATCH = "X"; String devName = device.getName(); if(devName.equals(DEVICE_WE_WANT_TO MATCH)) < // Connect. >

You can also use an app UUID

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

This will mean that only devices using this UUID will connect using your protocol, it’s an extra layer of security for the app.

In this, latter, case, we’re relying on one android device to be acting as a BT server and the other as a BT client.

Android bluetooth get connected devices, How can I get a list of all connected bluetooth devices for Android regardless of profile? Alternatively, I see that you can get all connected devices for a specific profile via BluetoothManager. You don’t need to pair a Bluetooth Low Energy device to connect to it. And ´getBondedDevices()´ would not return connected …

Programmatically connect to paired Bluetooth device

Okay, since this was driving me crazy, I did some digging into the source code and I’ve found a 100% reliable (at least on my Nexus 4, Android 4.3) solution to connect to a paired A2DP device (such as a headset or Bluetooth audio device). I’ve published a fully working sample project (easily built with Android Studio) that you can find here on Github .

Читайте также:  Aptx hd bluetooth кодек

Essentially, what you need to do is:

  • Get an instance of the BluetoothAdapter
  • Using this instance, get a profile proxy for A2DP:

adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);

where listener is a ServiceListener that will receive a BluetoothProfile in its onServiceConnected() callback (which can be cast to a BluetoothA2dp instance)

Method connect = BluetoothA2dp.class.getDeclaredMethod(«connect», BluetoothDevice.class);

String deviceName = "My_Device_Name"; BluetoothDevice result = null; Set devices = adapter.getBondedDevices(); if (devices != null) < for (BluetoothDevice device : devices) < if (deviceName.equals(device.getName())) < result = device; break; >> > 

Which, at least for me, caused an immediate connection of the device.

the best way I found to solve my problem was finding out that I can create a button that brings up the Bluetooth Settings screen. I didn’t realize you could do this, or I would have from the beginning.

startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); 

if the device is already paired , then you can use

if(device.getBondState()==device.BOND_BONDED) < Log.d(TAG,device.getName()); //BluetoothSocket mSocket=null; try < mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); >catch (IOException e1) < // TODO Auto-generated catch block Log.d(TAG,"socket not created"); e1.printStackTrace(); >try < mSocket.connect(); >catch(IOException e) < try < mSocket.close(); Log.d(TAG,"Cannot connect"); >catch (IOException e1) < Log.d(TAG,"Socket not closed"); // TODO Auto-generated catch block e1.printStackTrace(); >> 
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB"); 

the above code snippet is just to connect your device to an A2DP supported device. I hope it will work.

Android — Cant connect to device using bluetooth chat, I tried connect to other device like GPS Bluetooth, it also fails. App from play store . Bluetooth Terminal. connect to this two devices mentioned earlier without any problem. I could talk to them and receive text. What should I do with bluetooth example to work? AndroidManifest.xml

Connecting to a specific bluetooth port on a bluetooth device using Android

Ok, it’s been a while, but I found a solution to the problem. I actually intended to give up and use UUID, but I kept getting a Service Discovery Failed (IO)exception, and when I tried to find a solution to the service discovery issue, I found the solution to my original question. Ain’t life something?:)

Anyways, this is the link I stumbled upon, though you should note there is a mistake in the answer (they actually simply connected to port 1, instead of using a service UUID).

And after this short history lesson, here is the solution:

Using reflection, it is possible to create the Rfcomm socket connecting to a port number instead of UUID:

int bt_port_to_connect = 5; // just an example, could be any port number you wish BluetoothDevice device = . ; // get the bluetooth device (e.g., using bt discovery) BluetoothSocket deviceSocket = null; . // IMPORTANT: we create a reference to the 'createInsecureRfcommSocket' method // and not(!) to the 'createInsecureRfcommSocketToServiceRecord' (which is what the // android SDK documentation publishes Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] ); deviceSocket = (BluetoothSocket) m.invoke(device,bt_port_to_connect); 
  1. since we’re using Invoke, the first parameter is the object we’re invoking the method on, the second parameter of invoke is actually the first function parameter)
  2. There is also a secure version available (‘createRfcommSocket’), which accepts a bluetooth channel number as a single parameter (again, since this is invoke style, you’ll need to pass the object to invoke the method on, as mentioned in -1- )
  3. I found what appears to be a link to these functions’ prototypes
Читайте также:  Bluetooth car kit jieruibt 5508

Bluetooth Android connections are exclusively done via UUID. Each Bluetooth device has a UUID for every service it runs (see Bluetooth SDP).

You just give Android the UUID to watch for and, in client mode, it will find a socket to connect to automatically (including port). In server mode, it will wait for the specified device to initiate a connection using the specified UUID. The BluetoothSocket object is also valid when connection is established (use getInput/Output Stream) See Server Socket documentation and Client Socket documentation.

If you really want to check everything, you can see what Android decodes from the other device’s SDP and the UUID you provided.

Use this tutorial to get the Bluetooth interface (very easy to do). Then the code should look something like this:

IBluetooth ib =getIBluetooth(); Int otherDevicePort = ib.getRemoteServiceChannel(otherDeviceAddress, UUID); 

I’m using bluecove which allow me to do so with the function Connector.open() .

I use the following url: btspp://» + phoneID + «:» + phonePort

N.b.: Some options can be added (e.g.: authenticate=false; or encrypt=false; ).

With phoneID being the the being the Bluetooth address and phonePort the port number.

How to find the Bluetooth address? From this link:

  1. From the Home screen, open the app drawer, then open “Settings“.
  2. Select “System“. (Skip this step on some models)
  3. Scroll down to the bottom and tap “About Phone“, “About device“, or “About tablet“.
  4. Scroll down to the bottom and tap “Status“.
  5. Scroll down and the “Bluetooth address” will be shown in the list.

How to find the port number? I haven’t been able to find which port is supposed to be used yet. I used 5 and it works but I need to research why and if I want to change the phone I will need to know if I also need to change the port.

Android — connect to device with Bluetooth address on, First you will have to findout what profile the bluetooth device supports, For instance it could be a medical device that could use HDP profile or it could be using a simple RS232 over bluetooth. It is important to understand how the bluetooth connection is established for various profiles before you start writing code.

Источник

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