Problems with Reflection for createRfcommSocket

2020-07-25 23:20发布

This is odd. I am trying to set up Bluetooth SPP on a Droid X Android 2.3.4. I have included a few different methods from attempting to open an rfcomm Socket, one being reflection (needed for support of certain phones)

However, with the Droid X a strange thing happens. When I connect the first time to a Bluetooth device my app opens up and attempts SPP by first:

Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(mmDevice, Integer.valueOf(1));

And if it can't find the method, it tries the normal

mmSocket = mmDevice.createRfcommSocketToServiceRecord(SerialPortServiceClass_UUID);

This works correctly the first time through. But if I close my program then reopen it for some reason the reflection method then actually finds the method, attempts to connect doesn't have any errors, but it doesn't actually connect.

If I close the app, power cycle the bluetooth adapter on the phone and try again it will work correctly.

I am at a loss on what's going on, so any help would be greatly appreciated.

1条回答
Rolldiameter
2楼-- · 2020-07-26 00:04

Well I came up with a bandaid type fix that I am not happy with, but will work until I can find the root cause or better solution. I simply make a shared preference object that contains a "level" of which methods to try.

The levels are labeled 1-4, and if the level is set to a number <= to the current level it will try that method if no connection has been established.

if(level<=1){
success set level = 1
fail set level = 0
}

if(level<=2){
success set level = 2
fail set level = 0
}

...


if(level<=4){
success set level = 4
fail set level = 0
}
查看更多
登录 后发表回答