Rectangle 27 6

I will update this answer in a couple of days when I test service discovery and gatt read and write requests without a reboot.

EDIT: It turns out I was testing on a development firmware version (our sensor) that was causing issues if not paired. Our latest production firmware build works fine on the 2540s and 2541s.

EDIT: I did notice that on the Nexus 7 2013, connections are more stable when WiFi is turned off. I'd like to know if this helps anyone else.

EDIT: I seem to have had it backwards with pairing. Everything works fine when not paired. After pairing, I am experiencing the exact same symptoms as the OP. It's just not known yet if this is related to our firmware or the Android BLE API. Be careful if testing this because once paired, you may not be able to unpair due to a bug explained in 3b of this post.

I am consistently connecting and reconnecting to a CC2541 device without any sort of manual pairing or reboot.

For my opinion, there is no pairing necessary. The official docs don't comment pairing also. I also could perform write, read, characteristic changed notification without any pairing. However, just for a short time. Now it's shaky again... The SAMSUNG BLE SKD v2.0 also didn't require pairing and worked quite good.

Whether pairing is required or not is dependent up the device implementation. nrf8002 devices require pairing and the Samsung 2.0 and 1.2 API's both supported this. It seems like the official api support is having problems with the pairing aspect as after I pair a ble device, it seems impossible to unpair!

I have a work around for being unable to unpair. 1) go to your bt menu, select unpair, remove the ble device from the area or depower it, select the ble device in the bt menu and it'll try to pair and fail, then reset bluetooth. Upon reset the device will be unpaired.

Android 4.3 Bluetooth Low Energy unstable - Stack Overflow

android bluetooth bluetooth-lowenergy android-bluetooth android-4.3-jelly-bean
Rectangle 27 1

I came through an API in android called NSD ( Network Service Discovery) whether this will be useful for identifying the h/w connected through Wi-Fi and send commands to that... Suggest on this

android receive and send data through wifi connection to hardware - St...

android
Rectangle 27 4

Can you comment on the performance (speed-wise) and battery usage of setting up and maintaining a connection with another device?

@ajnatural with WifiP2pDnsSdServiceInfo there is no connection setup, it is zero configuration, multicast broadcast talk/listen. Performance will be unreliable as i mentioned in answer, and batter drain heavy due to it having to do broadcast. If are referring to regular WiFi P2P connection, once you discovered and established a connection, WiFi P2P will be in similar speedy/power-efficient as regular wifi connection.

Sending data in Android WiFi Direct service discovery instead of conne...

android wifi-direct
Rectangle 27 5

The confusion that may lead many people here is that you can use short code UUIDs to reference bluetooth services and characteristics on other platforms - for instance on iOS with CBUUID. On Android however, you must provide a full, 128-bit length UUID as specified in RFC4122.

The fix (as @Michael pointed out) is to prepend your 16bit or 32bit short UUID to the base bluetooth UUID. You can use these functions to make this a bit easier.

public static final String baseBluetoothUuidPostfix = "0000-1000-8000-00805F9B34FB";

public static UUID uuidFromShortCode16(String shortCode16) {
    return UUID.fromString("0000" + shortCode16 + "-" + baseBluetoothUuidPostfix);
}

public static UUID uuidFromShortCode32(String shortCode32) {
    return UUID.fromString(shortCode32 + "-" + baseBluetoothUuidPostfix);
}
UUID uuid = uuidFromShortCode16("FFF0");
"0000FFF0-0000-1000-8000-00805F9B34FB"

How to create UUID from string in android - Stack Overflow

android uuid bluetooth-lowenergy
Rectangle 27 2

JmDNS is a Java implementation of multi-cast DNS and can be used for service registration and discovery in local area networks. JmDNS is fully compatible with Apple's Bonjour.

android - Get list of devices in local network (LAN)? - Stack Overflow

android networking broadcast wireless
Rectangle 27 1

"The APIs Discovery Service provides only public methods that do not require authentication. In addition, unlike the requests you make to many other Google APIs, the requests you make to the Discovery Service API should not include an API key. If you do provide a key, the requests will fail. This behavior helps ensure that you don't accidentally disclose your API key when distributing tools that are based on the Google APIs Discovery Service."

So you can solve the problem by removing the key from your request entirely.

If you are using Google's javascript client to do this and the error occurs when loading further APIs, you have to unset the key first:

gapi.client.setApiKey( null );          
gapi.client.load( "plus", "v1", function( apiresponse ) { ... } );

To avoid setting and unsetting the key constantly, I load all the needed APIs before authentication, then set the API key and thus will no longer have the issue.

javascript - Google Plus API - Keyinvalid - Stack Overflow

javascript api google-api google-plus google-plus-one
Rectangle 27 1

Thanks for your answer ldx but I would need peer discovery as you indicated. Some further research appears to indicate XMPP as a suitable technology and there are now some services on offer, although these appear to be aimed at 'server' to client notifications. There is a good discussion here on XMPP and some more here although it would appear that there are still some issues to deal with such as polling v push, long-running open http connections and battery life. Xtify looks promising, especially their web service. I hope this provides suitable information to others looking at the topic of peer-to-peer data communication.

Since asking this question and researching some of the answers provided, I have decided to implement Google's C2DM. I hope this is the right decision as it is currently still in 'Labs' and could potentially be withdrawn.

android - Peer-to-Peer communication options - Stack Overflow

android json communication p2p
Rectangle 27 1

Thanks for your answer ldx but I would need peer discovery as you indicated. Some further research appears to indicate XMPP as a suitable technology and there are now some services on offer, although these appear to be aimed at 'server' to client notifications. There is a good discussion here on XMPP and some more here although it would appear that there are still some issues to deal with such as polling v push, long-running open http connections and battery life. Xtify looks promising, especially their web service. I hope this provides suitable information to others looking at the topic of peer-to-peer data communication.

Since asking this question and researching some of the answers provided, I have decided to implement Google's C2DM. I hope this is the right decision as it is currently still in 'Labs' and could potentially be withdrawn.

android - Peer-to-Peer communication options - Stack Overflow

android json communication p2p
Rectangle 27 0

Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
         tmp = (BluetoothSocket) m.invoke(device, 1);
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
tmp = device.createRfcommSocketToServiceRecord(SPP_UUID);

Wait, I have a few Bluetooth apps and I haven't found a situation where using reflection (getclass.getmethod) is necessary. Can you tell me a little more about what hardware you tried? I am very interested to know if reflection is actually necessary in certain situations.

The best I found was try the first method, which connects faster. Then on the Service Discovery fail implement the reflection in the exception. Also found that the same HTC phones also had issues with UDP detection as well, while Samsung and Motorola devices had no issues.

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.

Reading the source code for BluetoothDevice class in JellyBean, it seems that this creates an RFCOMM socket on channel 1. The javadocs are intentionally skipped, and the method is not exposed in the API. I have no idea of why this hack works, but it allowed me to communicate with a device allegedly lacking SPP profile, where no UUID worked.

And now another anonymous user comments: The suggested edit is using the exact same method as the code that doesnt work. The working code uses a different non-public method that doesnt require the uuid.

"Permission denied" exception is thrown for me although I have requested both BLUETOOTH and BLUETOOTH_ADMIN permissions. The moment I changed this code back to the one in BluetoothChat, the "Permission denied" exception was gone but the "Service discovery failed" exception came back. What should I do?

Got the same error as above when attempting to write an android application that connects to a Bluetooth scanner. This solution worked for me.

@Monsingor I can't comment either way, I just took the suggested edit - but please tell us why, or better yet edit and correct the answer.

@Rup The original code uses "00001101-0000-1000-8000-00805F9B34FB" as a UUID argument for createRfcommSocketToServiceRecord() function right from the beginning. I don't understand why you added an answer that proposes to do the same thing in a slightly different manner. Obviously, this wouldn't help.

java - Service discovery failed exception using Bluetooth on Android ...

java android bluetooth
Rectangle 27 0

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...

java - Service discovery failed exception using Bluetooth on Android ...

java android bluetooth
Rectangle 27 0

The error I was getting was Connection Refused when trying to connect over a bluetooth socket to my other devices. After much pain and research, I found that I could manually unpair my computers from my phone and then the bluetooth socket connects fine.

The strange thing is that I never even paired those devices, so I don't know how they got that way. But if you are getting Connection Refused, see if your Android device is paired to the machine you're connecting to, then manually unpair it, then try connecting with a bluetooth socket again.

Hope this saves someone a few hundred hours...

Can you elaborate on that? I seem to have a similar problem! It seems that Android forgets to update newly negociated Bluetooth link keys of an already paired device, or something like that. What kind of socket were you opening? Secure or insecure?

Unfortunately, I don't know enough about Bluetooth to comment on "link keys." I was trying to create an insecure connection from my Droid X2 to 3 computers, but I tired secure too. Each attempt failed with "Connection Refused." Initially I was getting "Service Discovery Failed", but for some unknown reason the error eventually changed. After much searching I found a post that mentioned manually unpairing devices (I don't have the link anymore). I tried unpairing out of frustration and somehow doing that allowed my connection attempt to go through. I continue to be perplexed by this.

I will figure it out eventually, I have a bluetooth chip on a custom pre-production hardware...I must find out why this bug occurs. All I can say so far is this: connection works ok after pairing(does not matter who starts the pairing process). The issue is after my device is powered off. It will want to renegociate link keys (reauthenticate). It does this, but Android closes the connection afterwards instead of accepting(no error message).

Android Bluetooth: Service Discovery Failed, connection to Desktop/Lap...

android bluetooth service-discovery bluecove
Rectangle 27 0

Sadly, none of these work :( I tried quite a lot of different services but got service discovery error for all 'generic' ones. But fair point, that was one of my guesses that I'm just connecting to the wrong UUID (and Android's API is too stupid to understand MAC/service/port addressing).

How to prevent Android bluetooth RFCOMM connection from dying immediat...

android bluetooth motorola rfcomm
Rectangle 27 0

you have to do a service discovery with the device you are trying to connect with, Get the UUID that it returns (which will be corresponding to the service that is running on the device and accepting connections) and then connect to it.

Android Bluetooth Where can I get UUID? - Stack Overflow

android bluetooth uuid
Rectangle 27 0

I worked through a similar learning process. I have tried to document what I learned in a series of examples.

This one might be of help:

It is for setting up a simple connection between an Android device and a PC via bluetooth. The examples contain the Android files as well as an SPP server in java and one in perl for the PC.

I'm working on this but still not working, I think I am doing somethings terribly wrong. Thanks for your interest.

java - Android Bluetooth Connection - Service Discovery Failed - Stack...

java android sockets bluetooth ioexception
Rectangle 27 0

This is very strange, but I simple all Thread.sleep(5000); before socket.connect() and it works without "Service Discovery Failed" exception.

java - Android Bluetooth Connection - Service Discovery Failed - Stack...

java android sockets bluetooth ioexception
Rectangle 27 0

The UUID you try to use is the Serial Port Profile UUID. It could be declared in code like

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

I tried your code with a Windows 8 laptop and a Nexus S. First I had to pair the devices from the Nexus. Then I started the server and used the Bluetooth SPP app to test the connection. It worked flawlessly. Then I started your code and it worked as well and it worked too.

I could reproduce the "Service discovery failed" exception when the server side was not started. Also, after I scanned all 30 channels with the createRfcommSocket method, the bluetooth stack on the phone got corrupted and I had to restart the device.

  • on the laptop make sure that the bluetooth is in discoverable state
  • (optional) turn off UAC and use an admin account to make sure you don't encounter any security bugs (I didn't have to do this but on the second start the firewall had to be opened for eclipse to enable debugging)
  • pair from the phone
  • use the SPP UUID, not a custom one
System.out.println(local.getBluetoothAddress());
acceptAndOpen()
  • test the connection with a third party app from the play store. I used this one in command line mode. Only the connection needs to be tested.
  • update the MAC address and run the app

Here is the output I got from the run:

Start service:btspp://localhost:0000110100001000800000805f9b34fb;name=EchoServer;authenticate=false;encrypt=false;
MAC 402CF454215C
Waiting for incoming connection...
Client Connected...
Exception Occured: java.io.EOFException
BlueCove stack shutdown completed
java.io.EOFException
    at java.io.DataInputStream.readChar(Unknown Source)
    at examples.bluetooth_spp_server.EchoServer.<init>(EchoServer.java:30)
    at examples.bluetooth_spp_server.EchoServer.main(EchoServer.java:42)

For the sake of completeness, here is the error that is returned under various conditions

javax.bluetooth.BluetoothStateException: Bluetooth not detected
java.io.IOException: Unable to start Service Discovery
java.io.IOException: Service discovery failed
TimeoutException

Theoretically pairing should happen automatically when a secure connection is initiated but in reality the pairing dialog may not appear in all cases on the phone or in Windows. This is a factor of uncertainty that needs to be considered if failures happen.

Thanks. But when I try the option 2 : the socket.connect() fail with a "connection timeout". Additionally, I'm not sure that the uuid of my server is not in the repository since when I call bluetoothDevice.getUuids() on the client I receive an array with the SPP-UUID + my custom UUID (if I define one randomly generated)

What version of android do you use?

Ok, I'll try to confirm again that this works. I have the same version on my device.

@ben75 I tested the whole scenario and updated the post. Btw: getUuids() for me returns the 0x1000, 0x1101, 0x1115, 0x1200 services in this order.

java - Bluetooth : Service discovery failed - Stack Overflow

java android bluetooth android-bluetooth
Rectangle 27 0

Maybe you can try adding thread.sleep for a second? See this discussion:

"The only way I've been able to fix the problem is by adding a thread.sleep for a second before closing the connection."

also see dan's two consecutive comments on this thread:

"I was able to get this to run only after separating the calls to findBT(); openBT();

but if I put findBT() in onCreate() and just use the button for openBT(); it works fine.

the excerpts from the second comment:

Set pairedDevices = mBluetoothAdapter.getBondedDevices();
mmDevice = mBluetoothAdapter.getRemoteDevice(00:06:66:46:5A:91);
if (pairedDevices.contains(mmDevice))
{
statusText.setText(Bluetooth Device Found, address:  + mmDevice.getAddress() );
Log.d(ArduinoBT, BT is paired);
}

where I entered the address of my Bluetooth device. The original code finds the device and returns the correct address, but mmSocket.connect(); generates an exception java.io.IOException: Service discovery failed

Thanks, it solved my problem. And now me facing another problem in the same application. The link for my next question is as follows: stackoverflow.com/questions/21568601/ Hope ypu will help me in solving this problem also. Thanks again.

Android Bluetooth: java.io.IOException: Service discovery failed - Sta...

android bluetooth inputstream serversocket outputstream
Rectangle 27 0

  • Yes. The official sample code should be able to make your quick start. Implement the function of service discovery is very easy. Only two steps: setting up a discovery listener with the relevant callbacks, and making a single asynchronous API call to discoverServices().
  • If you use the third-party library Advantage: It can make your application works below Android 4.1Disadvantage: Developing the function of service discovery would more complex. Because of you need write a background service to listen to broadcasts on the network.

Do you have PC version of your app? how to implement service discovery in your PC version of app?

Is Android NSD (Network Service Discovery) compatible with Bonjour ser...

android ios bonjour jmdns mdns
Rectangle 27 0

0x81 GATT_INTERNAL_ERROR
  • Turn off WiFi, onServicesDiscovered was never called.
onServicesDiscovered

I also test the same program on Galaxy S4 (Android 4.3) and it works well at all time.

Therefore, I believe that the BLE stack on Nexus 7 is not good.

If you can live with no WiFi, it may be OK, but if you can find some other Android 4.3 device, you shall try other devices.

That's some interesting information, but disabling other features (such as wifi), or restarting / rebooting everytime I want to use this is not a valid solution. I need something that works with wifi, and doesn't require resets / cycling Bluetooth radios, etc. I have since posting this successfully implemented a version on iOS that works without any issues. I think this needs to be fixed by google or android or the phone manufacturers, so that we don't have to lose features or jump though hoops to get a reliable system running.

Bluetooth Low Energy Service Discovery with Android 4.3 on Nexus 4 - S...

android bluetooth-lowenergy nexus-4
Rectangle 27 0

You can use jMDNS to do Bonjour service advertising/discovery with Android, it's pretty mature (or you can even roll your own, it's not that difficult :)

As for Bluetooth and NFC, I'm not sure; it sounds like you'll need to administer some single point of registration/coordination for whatever service you're advertising/consuming.

Thanks so much for the answer. I just have a few questions. About your last point, the thing is, I think bonjour over Bluetooth is the perfect thing, as it allows you to discover devices locally and then use IP-over-bluetooth to connect to them, I just can't find any documentation or examples. Do you know of any?

My understanding is that the mDNS responder in iOS will advertise Bonjour services over any supported network interfaces, including Bluetooth. You shouldn't have to change your NSNetService code for it to work, although I haven't worked with Bluetooth PANs extensively.

That was in all versions until 5. Apple has this whole tech q and a about how it's changed.

I saw that somewhere, didn't read into it too much though. Having written a couple of mDNS responders I'd consider myself familiar with Bonjour, but I've never used it over Bluetooth unfortunately :/

Thanks. I think I found a little bit of documentation and sample code in the depths of the apple site, so I'll look there. Thanks for the answer!

android - Does Apple's Bonjour protocol work over cellular connections...

android ios bluetooth nfc bonjour