Android pairing does not work - "connection reset by peer" - android

As the title explains I'm having a hard time sending some data via Bluetooth to my PC. I'm trying to establish a connection with my android phone as client and my PC as server. When I'm trying to actually establish a connection via BluetoothSocket.connect() my phone prompts for a pin. After entering it my PC also prompts for the same pin but before I can enter it, the connect() - method throws an IOException. I assume that the connect()-Method times out before I can enter the correct pin on my PC, but how can I get it to wait long enough for me to enter the PIN?
EDIT: After Re-Pairing the PC with my Phone it worked, because the pairing dialog doesn't appear in my app anymore. If I unpair the PC and start my app, the pairing dialog pops up but disappears after several seconds and the socket throws an exception ("connection reset by peer"). Apparently the connection is reset before the pairing is done, but why?
Here is my code:
private void connectToDevice(BluetoothDevice device)
{
mBluetoothAdapter.cancelDiscovery();
BluetoothSocket socket = null;
try
{
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101- 0000- 1000-8000-00805F9B34FB"));
}
catch (IOException e)
{
Log.e("HeliRemote", "Couldn't get socket.");
return;
}
try
{
socket.connect();
}
catch (IOException e)
{
try
{
socket.close();
}
catch (IOException e1)
{
Log.e("HeliRemote", "Couldn't close connection");
}
// That's the message I get in LogCat
Log.e("HeliRemote", "Couldn't connect to Socket.");
return;
}
Log.i("HeliRemote", "connected.");
}
I would be glad if somebody could give me any good words of advice regarding the problem.

Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mBluetoothSocket = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);
// mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (NoSuchMethodException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalAccessException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (InvocationTargetException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
}
}
try this one...

Related

How to make a Bluetooth SPP connection process more reliable?

We are about to release the new version of our software, and for the version afterward, our goal is to make the connection process for our Bluetooth SPP connections more reliable. We use the RN42 module in our products, and currently, at times it may take more than one try to connect to our boards.
Here is my current code:
class ConnectThread extends Thread {
BluetoothDevice mDevice;
public ConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
btSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not create socket!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
btSocket.close();
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
btAdapter.cancelDiscovery();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("whatever", "InterruptedException: " + e.getMessage(), e);
}
try {
btSocket.connect();
Log.i("Treadmill", "After Connect");
} catch (IOException ioe) {
Log.i("Treadmill", "Trying Fallback");
try {
Method m;
try {
btSocket.close();
m = mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});
btSocket = (BluetoothSocket) m.invoke(mDevice, 1);
Thread.sleep(500);
btSocket.connect();
} catch (IllegalArgumentException e) {
Log.e("whatever", "IllegalArgumentException: " + e.getMessage(), e);
} catch (IllegalAccessException e) {
Log.e("whatever", "IllegalAccessException: " + e.getMessage(), e);
} catch (InvocationTargetException e) {
Log.e("whatever", "InvocationTargetException: " + e.getMessage(), e);
} catch (NoSuchMethodException e) {
Log.e("whatever", "NoSuchMethodException: " + e.getMessage(), e);
} catch (InterruptedException e) {
Log.e("whatever", "InterruptedException: " + e.getMessage(), e);
}
} catch (IOException ioe2) {
Log.e("Treadmill", "Failed to connect to Bluetooth device: " + ioe2.getMessage());
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT, 0, 0, getResources().getString(R.string.connerr) + ": " + ioe2.getMessage()).sendToTarget();
try {
btSocket.close();
} catch (IOException localIOException2) {
Log.e("Error", "IO Exception!");
}
return;
}
}
eventHandler.obtainMessage(MESSAGE_CONNECT, 0, 0, "").sendToTarget();
synchronized (this) {
connectThread = null;
}
manageConnectedSocket(btSocket);
}
}
Even with the fallback to reflection the connection intermittently fails on some devices. I get the following error:
find_rfc_slot_by_id unable to find RFCOMM slot id: XX (XX being a number that increments on each attempted connection).
followed by this:
Failed to connect to Bluetooth device: read failed, socket might closed or timeout, read ret: -1
Does anyone know how to avoid these errors.
Interestingly, for comparison. I am testing on two tablets. One tablet, the Samsung Galaxy Tab 4 seems to work extremely well, while another, the Astro Tab A10, seems to be a bit more intermittent unless you wait several seconds between connecting and disconnecting.
For more reliable connection means even app was closed, Bluetooth should be keep connected in the background.
Below is the working solution I followed in my app to keep Bluetooth connection background.
First create a class which extends service, because service runs in the background even app closed until you call stopService or stopSelf methods
while starting BluetoothService class pass Bluetooth Mac address to connect and run in the background.
Sample code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
String deviceg = intent.getStringExtra("bluetooth_device");
if (deviceg != null){
connectToDevice(deviceg);
}
}
return START_STICKY;
}
Below is the connect to device method which identifies mac Address into Bluetooth Device.
public synchronized void connectToDevice(String macAddress){
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectBtThread(device);
toast("connecting");
mConnectThread.start();
}
This is my Thread class inside BluetoothService which runs in a separate thread
Code:
private class ConnectBtThread extends Thread{
private final BluetoothSocket mSocket;
private final BluetoothDevice mDevice;
public ConnectBtThread(BluetoothDevice device){
mDevice = device;
BluetoothSocket socket = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(B_UUID));
} catch (IOException e) {
e.printStackTrace();
}
mSocket = socket;
}
#Override
public void run() {
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
try {
mSocket.connect();
Log.d("service","Bluetooth one running (connected)");
} catch (IOException e) {
try {
mSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
connected(mSocket);
}
public void cancel(){
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It works perfectly fine for our app.
If you want to access service methods bind this service to your activity

How to disconnect A2DP profile Bluetooth Connection?

I am working on A2DP connection with headset and other Bluetooth device but when I connect Bluetooth device but when I Disconnect but It didn't disconnect with it. My code is:
try {
Method connect = mA2dpService.getClass().getDeclaredMethod("disconnect", BluetoothDevice.class);
connect.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
Finally I found
Call getProfileProxy to get a2dp proxy
adapter.getProfileProxy(c, listner, BluetoothProfile.A2DP);
listenr should implement onA2DPProxyReceived.
Then Callback onA2DPProxyReceived will be called.
public void onA2DPProxyReceived (BluetoothA2dp proxy) {
Method disconnect = null;
try {
disconnect = BluetoothA2dp.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
BluetoothDevice device = findBondedDeviceByName(mBtAdapter, myDevice);
disconnect.setAccessible(true);
try {
int result = disconnect.invoke(proxy,device);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
Refer to sites below
getDeclaredMethod : https://www.tutorialspoint.com/java/lang/class_getdeclaredmethod.htm
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothA2dp.java
Invoking : https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

Android - Bluetooth connection InputStream close crashes my app

I have an Android application where I connect to a bluetooth device. When I shut the device off, the application tries to disconnect. So I try to close the inputstream the outputstream and the socket. Even though I have a try catch on each close try, the app crashes when it tries to close the inputstream. Any ideas? Code example:
private void resetConnection() {
if (mmInputStream != null) {
try {
mmInputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE InputStream", e);
}
mmInputStream = null;
}
if (mmOutputStream != null) {
try {
mmOutputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE OutputStream", e);
}
mmOutputStream = null;
}
if (mmSocket != null) {
try {
mmSocket.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE mmSocket", e);
}
mmSocket = null;
}
}
Any suggestions? Thanks

Does a thread stops executing and contiune? It is just confusing

I added logs to the code just to understand the order and time of its execution, but so far it is just confusing!
When I execute this code and start the server, I get these outputs
"start server", "ServerThread"
"listening", "ServerThread"
"connection arrived", "ServerThread"
And stops there, and when I connect to the server I only get
"connection accepted", "ServerThread"
As if it was hanging on
socket = serverSocket.accept();
Isn't it suppost to exit the try for some sort of exception and print the whole thing again?
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
Log.e("start server", "ServerThread");
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO error at starting server", "ServerThread");
} catch (Exception e) {
Log.e("Exc at starting server", "ServerThread");
}
while (!Thread.currentThread().isInterrupted()) {
Log.e("listening", "ServerThread");
try {
Log.e("connection arrived", "ServerThread");
socket = serverSocket.accept();
Log.e("connection accepted", "ServerThread");
CommunicationThread commThread = new CommunicationThread(
socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
Log.e("IO error at accept", "ServerThread");
} catch (Exception e) {
Log.e("Exc at accept", "ServerThread");
}
}
}
}
This is a blocker method, it will block until you receive a connection.
take a look at the docs: http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#accept()

Android bluetooth code working fine on 2.2 but not on 2.3 or 2.3.3

i am using code to make Bluetooth connection,
public void run()
{
try
{
Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mBluetoothSocket = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);
// mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (NoSuchMethodException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalAccessException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (InvocationTargetException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
}
}
it is working fine on a Karbonn device which is android 2.2 and when i try same code on Samsung Galaxy Y and Sony Ericson Xperia mini then it does not work...
What can be the issue..Kindly assist...
Did u set the permissions in the manifest?
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
And whats exactly your exception?
EDIT:
according to this
http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_ACL_DISCONNECTED
it's a low level exception that shouldnt occur.
How to programmatically tell if a Bluetooth device is connected? (Android 2.2)
Does this help you?

Categories

Resources