Failing bluetooth sequence - android

I'm trying to make a simple connection sequence to a serial bluetooth device at the beginning of my app. Right now, all of this is inside onCreate ():
BT = BluetoothAdapter.getDefaultAdapter();
BT.enable();
if(!BT.isEnabled()) {
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, REQUEST_ENABLE);
BT.enable();
Toast.makeText(getApplicationContext(), "Bluetooth On.", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else {
Toast.makeText(getApplicationContext(), "Bluetooth On.", Toast.LENGTH_LONG).show();
}
pairedDevices = BT.getBondedDevices();
pDevices = new ArrayList<BluetoothDevice>();
if (pairedDevices.size()>0) {
for(BluetoothDevice bt : pairedDevices)
{
pDevices.add(bt); //Get the device's name and the address
}
}
else {
Toast.makeText(getApplicationContext(), "Nothing paired.", Toast.LENGTH_LONG).show();
}
try {
BluetoothDevice dispositivo = BT.getRemoteDevice(pDevices.get(0).getAddress());
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
btSocket.connect();
}
catch (IOException e){
Toast.makeText(getApplicationContext(), "Failed.", Toast.LENGTH_LONG).show();
}
The goal is to connect to the first available paired device. So far it always displays "Failed." even when I have an unconnected paired device sitting next to the phone.
Should I be doing this somewhere else in the app? I'm not really concerned with delaying the main activity since this is for a personal project.
Edit: spelling

All BT 2.1 devices and newer ones require the secure connection, so use the createRfcommSocketToServiceRecord instead of the createInsecureRfcommSocketToServiceRecord.

I actually figured it out... It was trying to connect to only the first paired connection. I put the try catch on a for loop, now it connects fine :)

Related

BLE - First connection with app is not working

I'm working with device Texas, for management of the LED, in my custom Android app. The device has enabled the pairing with a default passkey 000000. In my code for app, I have this part of code for reading the paired of device.
private void getpaireddevices(){
Set<BluetoothDevice> devicesArray = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if(devicesArray.size() > 0) {
for(BluetoothDevice device : devicesArray) {
device.getName();
device.getAddress();
}
}
}
In this moment, when I enable the BLE the app found the device, it connect but not works. For this to work I should exit and reconnect with my device. Why?
This is possible if the device is already bonded. Call removeBond() method to clear previous bonding state.
device.removeBond();
For check bonding state of BluetoothDevice, use getBondState().
Ble gatt connection success rate is different per device by device. You may need disconnect ble by hidden method, if your connection fails continuously.
Please read this:
BLE Device Bonding Remove Automatically in Android
The method unpairDevice() will unpair bluetooth connection.
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice bt : pairedDevices) {
if (bt.getName().contains("String you know has to be in device name")) {
unpairDevice(bt);
}
}
// Function to unpair from passed in device
private void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) { Log.e(TAG, e.getMessage()); }
}

Monitoring the connection of a paired bluetooth device

I have written the code which returns me a list of all the paired bluetooth devices of a android device.One among the list of paired bluetooth devices is my laptop as well.
Now my question is
Is there a way I can monitoring the bluetooth connectivity status between the laptop and the android device.The output which I need is "Connected" if there is a bluetooth connection present and "Disconnected" if there is no bluetooth connection
The android version is 2.1.Eclair
Before I proceed further , I have some questions.
->Should I test this application when I connect the laptop and device through USB?
->How to run it on a separate thread or from an AsyncTask?
->The above code is not working for me if I connect the device and the laptop through USB and then launch the application. Even though the laptop and the phone are nearby and they are paired, I am not able to see a connected status in the phone.
The code which I have written is as follows
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_);
out = (TextView) findViewById(R.id.textView1);
// Getting the Bluetooth adapter
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// out.append("\nAdapter: " + adapter);
// Check for Bluetooth support in the first place
// Emulator doesn't support Bluetooth and will return null
if (adapter == null) {
out.append("\nBluetooth NOT supported. Aborting.");
return;
}
// Starting the device discovery
out.append("\nStarting discovery...");
adapter.startDiscovery();
out.append("\nDone with discovery...");
// Listing paired devices
out.append("\nDevices Pared:");
Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter()
.getBondedDevices();
for (BluetoothDevice device : devices) {
out.append("\nFound device: " + device);
out.append("\n The name is: " + device.getName());
out.append("\n The type is: "
+ device.getBluetoothClass().getDeviceClass());
Method m;
try {
System.out.println("Trying to connect to " + device.getName());
m = device.getClass().getMethod("createInsecureRfcommSocket",
new Class[] { int.class });
BluetoothSocket socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
out.append("Connected");
} catch (Exception e) {
e.printStackTrace();
out.append("\nDisconnected");
}
}
}
Which android version you are using?
You must have the permission on your AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH" />
You can try the code below, but be sure to run it on a separate thread or from an AsyncTask or your UI can hang up.
This will check for your paired devices and try to connect to each one. If it is successful then it prints Connected on logcat or else it prints Disconnected.
private void checkPairedPrinters() throws IOException {
Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
for (BluetoothDevice device : devices) {
Method m;
try {
System.out.println("Trying to connect to " + device.getName());
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
BluetoothSocket socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
System.out.println("Connected");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Disconnected");
}
}
}

Pairing to a CC2540 Bluetooth LE Device

I am trying to connect to a BLE devices based on CC2540 from TI (I have the keyfob from TI, and another device from connectblue OLP425) with my Motorola RAZR, the only succes I had so far is an app named Propagation on the market that I don't have access to the sources.
I tried to connect to the device with this code but the biggest thing I don't understand is the UUID,
I downloaded an app on a iPad 3 and I found a device has the following UUID
00000000-0000-0000-ff31-1a064f8c5966
private static final UUID SPP_UUID = UUID.fromString("00000000-0000-0000-ff31-1a064f8c5966");
BluetoothDevice bd =BluetoothAdapter.getDefaultAdapter().getBondedDevices().iterator().next();
//I only have I device paired that is the Bluetooth Low Energy Device so using the first Device returned by the iterator is fine.
try {
BluetoothSocket bs = bd.createRfcommSocketToServiceRecord(UUID);
bs.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
All I get is a Service discovery failed in logcat
In almost all the example everyone is using
00000000-0000-1000-8000-00805f9b34fb
If I go further in the app it syas that the battery service is UUID 0x180f
I would just like to create an app the read the value of this service which is a simple decimal value
anyone has any succes pairing with a BLE device in the past?
thank you
Jonathan
I've been able to connect to my CC2540 with the Heart Rate Monitor.
I flashed the firmware using the CCDebugger and using 0000180d-0000-1000-8000-00805f9b34fbas the UUID i've been able to read a value.
Using the Motorola_BLE_profile sample app with some modifications.
primaryServices = mGattService.getGattPrimaryServices(device);
if (primaryServices == null) {
String message = "Connection failed !";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
return;
}
for (i = 0; i < primaryServices.length; i++) {
Log.v(TAG, "primary service " + primaryServices[i]);
if (primaryServices[i].equalsIgnoreCase(hrmUUID)) {
try {
status = mGattService.connectGatt(device, hrmUUID, callback1);
if (status == true){
mDevice = device;
mLeState = CONNECTING;
BluetoothLeReceiver.isDevicePickerPending = false;
} else {
String message = "Connection failed !";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(TAG,"Exception while calling gatt Connect");
}
return;
if (i == primaryServices.length) {
Log.v(TAG,"Primary Service not found");
String message = "Connection failed !";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}

Android Bluetooth COM port

I have spent some time researching Android's ability to communicate with bluetooth devices that are designed to communicate over a Bluetooth COM port on a PC. I haven't been able to find a definitive answer, so I thought I'd ask here. I want to make sure that this is possible with Android.
I am new to Bluetooth communications, but the research I've done so far lead me to RFCOMM which somewhat sounded like what I wanted. Unfortunately, I'm still unable to confirm that this is in fact possible.
Any help/resources on this would be greatly appreciated.
Yes, Android can connect to Bluetooth COM ports on PC's. I am currently developing such an application. Here is a code example (Ite requires the bluetooth permissions te be set in the Manifest.xml file):
<uses-permission android:name="android.permission.BLUETOOTH" />
Java:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
// Device does not support Bluetooth
finish(); //exit
}
if (!adapter.isEnabled()) {
//make sure the device's bluetooth is enabled
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
}
final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
mac = "00:15:83:3D:0A:57"; //my laptop's mac adress
device = adapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
// Get a BluetoothSocket to connect with the given BluetoothDevice
BluetoothSocket socket = null;
OutputStream out = null;
try {
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (IOException e) {}
try {
socket.connect();
out = socket.getOutputStream();
//now you can use out to send output via out.write
} catch (IOException e) {}

Connecting with embedded device over bluetooth? [duplicate]

I'm currently working on an Android application that connects to an instrument via Bluetooth and need to write string commands and receive string responses back. Currently I have the connect/read/write working for TCP/IP over Wi-Fi and now trying to implement Bluetooth. But I am running into some roadblocks. I have been searching the web trying to find examples of something similar and haven't had any luck. I have been using the Android developer resource example: Bluetooth Chat as my main reference point.
My current code seems to work.. Then it throws a Service Discovery Failed exception at the point of the connection. I am using the DeviceListActivity class to do the discovery and selecting of the device I want to connect to. It returns anActivityResult and then my Bluetooth class waits for it to handle that and then does the connect to it. The code beneath is almost identical to the Bluetooth Chat App.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!m_BluetoothAdapter.isEnabled())
{
m_BluetoothAdapter.enable();
}
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = m_BluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
}
else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
This is my connect function:
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private void connect(BluetoothDevice device) {
m_Device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
}
catch (IOException e) {
}
m_Socket = tmp;
m_BluetoothAdapter.cancelDiscovery();
try {
// This is a blocking call and will only return on a
// successful connection or an exception
m_Socket.connect();
}
catch (IOException e) {
try {
m_Socket.close();
}
catch (IOException e2) {
}
return;
}
}
Hopefully, whatever I am doing wrong is simple, but I'm afraid it's never that easy. This is my first time doing any Bluetooth development, and maybe I'm doing something blatantly wrong... But I'm not sure why I get the service discovery failed exception.
You can pair/find the device at all times manually on the phone... It does require a passcode, but I don't think that is the problem that I am having.
After three days I got it figured out thanks to some very helpful posts.
I had to replace:
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
with:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
and voilĂ  it works!
As of API 15 you can use the following method:
Try replacing your UUID with the return value of getUuids() method of BluetoothDevice class.
What worked for me was something like this:
UUID uuid = bluetoothDevice.getUuids()[0].getUuid();
BluetoothSocket socket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
The reason this works is that different devices support different UUIDs and by getting the UUIDs of the device using getUuids you are supporting all features and devices.
Another interesting new method (supported since API 14) is this: BluetoothHealth.getConnectionState. Haven't tried it but looks promising...
This was a suggested edit from an anonymous user attempting to reply to the accepted answer.
One big difference between your before and after code is the UUID you are passing. I found my answer here: http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createRfcommSocketToServiceRecord(java.util.UUID)
I had to replace:
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
with:
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
tmp = device.createRfcommSocketToServiceRecord(SPP_UUID);
and voila it works!
The original code is for a peer to peer android app. It makes no sense to use the app UUID when connecting to a simple serial bluetooth device. Thats why discovery fails.
So as it mentioned above, the point is that you need to use the UUID that the server is waiting for.
If you are connecting to a bluetooth device, such as a headset or mouse, you need to check which UUIDs the device is listening for. You can see the UUIDs like this.
UUID[] uuids = bluetoothDevice.getUuids();
And if you want to know what these UUIDs mean, see this.
This is a realy old one question but i found that using the createInsecureRfcommSocketToServiceRecord() instead of createRfcommSocketToServiceRecord() along with the getUuids() previously mentioned do the trick for me
UUID uuid = bluetoothDevice.getUuids()[0].getUuid();
BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);

Categories

Resources