Ok, I will try one more time.
I have a device sdptool in ubuntu the following is stated from my device:
# sdptool browse C0:1B:DC:1F:E2:F1
Browsing C0:1B:DC:1F:E2:F1 ...
Service Name: OBEX Object Push
Service RecHandle: 0x10000
Service Class ID List:
"OBEX Object Push" (0x1105)
Protocol Descriptor List:
"L2CAP" (0x0100)
"RFCOMM" (0x0003)
Channel: 9
"OBEX" (0x0008)
Profile Descriptor List:
"OBEX Object Push" (0x1105)
Version: 0x0100
As you can se the device does support the RFCOMM protocol, and OBEX for file transfer. I have a simple code for my android app which tries to connect to this device over a insecure RFCOMM channel, just for no user interaction. I want to connect to this device, so Iam using the device mac-address for connection, and the socket is ready, logcat says so.
But I only get the error:
Connection refused
Have in mind that the mac-address in the java code is different from the following listed above.
So here is my code:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//MY_UUID = new UUID(0x0100 , 0x1000);
// MY_UUID = UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812");
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BluetoothSocket tmp = null;
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:1B:DC:0F:EC:7E");
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IllegalAccessException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InvocationTargetException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
try {
tmp.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(), "Socket closed!" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
boolean con = tmp.isConnected();
if(con)
Toast.makeText(getApplicationContext(), "Connection was made!", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Connection was not made!", Toast.LENGTH_LONG).show();
}
});
}
}
I've read several places that it should work by un-pairing and pair again, but this doesn't solve my problem.
Well, your question is over a month old, but in case you're still looking for the answer, here's one:
sdptool indicates that your RFCOMM channel is 9, but in your code you have:
tmp = (BluetoothSocket) m.invoke(device, 1);
Instead of 1 as your last argument, try 9 (if that doesn't work, try other integers, like 2 through 15).
You may also want to check out this answer.
There seem to be many variations of this question on Stack, but not a lot of understanding of the "standard" recommended code (i.e., the bluetooth chat sample modified with the lines that define and invoke "Method m")--I know because I'm one of those people who struggled with this. I was trying to connect my phone to my MacBook, and got the "connection refused" message until I realized that I needed to use 5 in the line of code above.
Related
I am building an app in Android Studio, and using a sql server, the app works great on my home WIFI network. I manage to connect to the server and do enter / read / update the data.
But the problem is that outside the home network the app does not work, why?
(its work fine in the home wifi, but when i'm going out of range of my wifi, its not working\connecting)
The SQL SERVER is on my home computer (meaning the same IP)
how to make it work on any android phone app and Everywhere ?
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "192.168.1.15";
String classes = "net.sourceforge.jtds.jdbc.Driver";
String db = "myDB";
String un = "mtun";
String password = "mypw";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL;
try {
Class.forName(classes);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"+db+";user=" + un+ ";password=" + password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERROR-1", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERROR-2", e.getMessage());
} catch (Exception e) {
Log.e("ERROR-3", e.getMessage());
}
return conn;
}
}```
I'm using the library Jamod and I have trouble reading the record, what I want is to read only the record number 300 PLC I'm connected, but I get read error (enters the catch). Thanks for your help
package com.JR.scada;
import java.net.InetAddress;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.net.TCPMasterConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity{
TextView text, depurar;
EditText IP;
Button boton;
int i=0;
TCPMasterConnection con = null; //the TCP connection
ModbusTCPTransaction trans = null; //the Modbus transaction
InetAddress addr = null; //direccion del esclavo
int port = Modbus.DEFAULT_PORT;//puerto por defecto 502
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.lblRegistro);
IP = (EditText) findViewById(R.id.txtIp);
depurar = (TextView) findViewById(R.id.txtdepurar);
boton = (Button)findViewById(R.id.btnVerRegistro);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
super.onStop();
//Close the TCP connection
con.close();
}
public class conectar extends AsyncTask<String,String,Integer>{
ReadInputDiscretesRequest req = null; //the request
ReadInputDiscretesResponse res = null; //the response
int startReg;
protected void onPreExecute() {
try {
//IP address;
addr = InetAddress.getByName("212.170.50.238");
} catch (Exception e) {
Log.d("MODBUS","IP error", e);
}
}
protected Integer doInBackground(String... urls) {
try {
// Open the connection
con = new TCPMasterConnection(addr);
con.setPort(port);
con.connect ();
try {
startReg = 300;
// Prepare the request
req = new ReadInputDiscretesRequest (startReg, 1);
// Prepare the transaction
trans = new ModbusTCPTransaction(con);
trans.setRequest(req);
// execute the transaction
trans.execute();
// get the response
res = (ReadInputDiscretesResponse) trans.getResponse ();
} catch (Exception e) {
Log.d("MODBUS", "Error in reading/writing");
return 1;
}
} catch (Exception e) {
Log.d("MODBUS","connection error", e);
return 1;
}
return 0;
}
protected void onPostExecute(Integer bytes) {
if(con.isConnected()){
depurar.setText("conecta");
}
text.setText("Digital Inputs Status=" + res.getDiscretes ().toString () );
}
}
public void onClick(View v) {
// int startReg;
conectar conectamos = new conectar();
conectamos.execute("hola");
}
error:
08-21 10:01:57.554: D/MODBUS(3322): Error in reading/writing
Without knowing more about the modbus configuration on your slave PLC, my first suggestion is to try a different value for startReg, and see if the error persists. This will rule out problems with your Java.
Some test numbers that should work: 0,1,7,8
They may not all work, but at least one of them should return successfully.
If none of them return successfully, there may be a problem on the PLC configuration, or a problem with your request code.
If one of the test numbers is successful, you should post your results. If so, this means that you are attempting to access a memory location that does not exist on the PLC. If you access undefined PLC memory locations, often the PLC will abort the request (it does not just send back '0').
Followup remarks:
If you find that your code works when using different values for startReg, but not for 300, the reason has to do with memory mapping on the PLC, and this can be different for each brand/model of PLC (post your PLC brand/model if available).
You say in your question 'record 300'. When working with PLC, you usually don't refer to memory as a record. Are you trying to access Bit 300, Byte 300, Word 300, DoubleWord 300?
The real question you need to be asking, is 300 the actual modbus address you want to read, or is 300 how the PLC address is mapped (such as the 300th I/O slot, not necessarily the 300th WORD). It may be required to convert between octal, decimal, and hexidecimal addresses. Or, you may need to re-index an address (some PLCs like to start counting at 1, but generally modbus starts counting at 0).
Perhaps you meant to read BIT 300 (not record 300), which would then be 12th BIT in the 18th WORD, so it would look like this:
//
startReg = 17;
// Prepare the request
// Your 300th bit should be the last value returned.
req = new ReadInputDiscretesRequest (startReg, 12);
The different values I suggested for startReg are meant to help you discover how your PLC Inputs are mapped into modbus addresses by your Java library. This might help with number conversions.
If you keep getting exceptions in your catch block, you might want to find out more about the error.
Try changing this line from your original code:
try {
//...
} catch (Exception e) {
Log.d("MODBUS", "Error in reading/writing");
return 1;
}
into this:
try {
//...
} catch (Exception e) {
Log.d("MODBUS", e.getMessage() );
return 1;
}
Hopefully the exception will tell you more about exactly why its failing. Post those results.
If you are getting a NULL message, you might try using a debugger to manually inspect your connection instance.
I'm newbie in Android programing, and I wanted to write a piece of code which simply send a string on 127.0.0.1 and I will be able to watch it on netcat but the problem is when I try it on my android project nothing happen, so I've tried in a usual java project and everything work well.
So after a lot of research I've find... nothing
My android code :
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.net.*;
import java.io.*;
public class MainActivity extends Activity {
public static final int MON_PORT = 5001;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bouton2 = (Button)findViewById(R.id.envoi);
bouton2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
int port=MON_PORT;
InetAddress adresse = InetAddress.getByName("localhost");
DatagramSocket socket;
String leMessage = "test";
int longueur = leMessage.length();
byte[] message= new byte [longueur];
message = leMessage.getBytes();
socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(message,longueur,adresse,port);
socket.send(packet);
System.out.println("test d'execution");
socket.close();
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
And I've checked my AndroidManifest.xml and the permission :
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>
are not between the applications tag
I use an AVD based on Android API 7 but I've tried on an another AVD with API 16 but results are the same, could someone help me to find what's wrong ?
Thanks
The actual problem is that your PC has no access to the UDP packet you are sending because that packet is being sent on a different IP address that device "emulator" uses through the Loopback mechanism.
Here is the thing. You can safely assume that the Android emulator is a remote machine that is remotely connected to your PC through an IP network, it has its own IP address and can communicate with your PC. You can't just use loopback IP to communicate with your PC over IP. Please use 10.0.2.2 instead as specified in this documentation page Emulator.
Using that IP you will be able to see the packets in netcat.
Iam trying to connect my android device with a bluetooth compatible device. I know the mac-address of this device, as you can see in my code below. I also made several Toasts just to verify the steps in the code. It seems that I manage to create tmp = device.createRfcommSocketToServiceRecord(MY_UUID); I assume this because the Toast raises a message saying some bluetooth object address, in this line of code:
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
But the code failes semantically when I do a tmp.connect(); I am working on API level 15, android 4.0
This i my piece of code
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ba = BluetoothAdapter.getDefaultAdapter();
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
boolean b = ba.checkBluetoothAddress("00:1B:DC:0F:EC:7E");
BluetoothSocket tmp = null;
//If valid bluetoothAddress
if(b) {
final BluetoothDevice device = ba.getRemoteDevice("00:1B:DC:0F:EC:7E"); //Getting the Verifier Bluetooth
//Trying to create a RFCOMM socket to the device
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No connection was made! Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
//Print out the sockets name
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "FALSE, No bluetooth device with this address", Toast.LENGTH_LONG).show();
}
}
});
}
}
I am aware of that this should be done in a separate thread, and yes, I read the Bluetooth Chat example provided by Google.
Can someone help me out?
EDIT
This is the only thing I got from LogCat:
07-06 10:10:22.085: V/BluetoothSocket.cpp(14019): ...fd 63 created (RFCOMM, lm = 26)
EDIT 2
Ok, now got a new error, but its a better error. When i press the connect button, the phone asks for the pin code for pair the devices, but its already paired! After I paired it for the second time, the error says: Connection refused and another exception says, timeout.
you can use this code:Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mySocket = (BluetoothSocket) m.invoke(device, 1);
I'm developing a program in which, from an Android Phone, I have to connect as a client to a Bluetooth medical sensor. I'm using the official Bluetooth API and no problem during connection (SPP profile), but when I end the socket, the sensor is still connected to my phone (although I have close the connection).
Are there any way to make a Bluetooth disconnection? I think there is an intent called ACTION_ACL_CONNECTED, which does that. Can anyone explain me how to use this?
Thanks in advance.
EDITED: Here is the code, if anyone needs additional info, it's a Nonin 4100 medical sensor.
Set<BluetoothDevice> pairedDevices = Activa.myBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
String name = device.getName();
if (name.contains("Nonin")) {
try {
found = true;
// socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
// handler.sendEmptyMessage(5);
// Activa.myBluetoothAdapter.cancelDiscovery();
// socket.connect();
BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress());
Method m;
try {
m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1));
handler.sendEmptyMessage(5);
socket.connect();
} catch (Exception e) {
handler.sendEmptyMessage(7);
e.printStackTrace();
break;
}
handler.sendEmptyMessage(6);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] retrieve = { 0x44, 0x31};
out.write(retrieve);
byte [] ack = new byte [1];
in.read(ack);
if (ack[0] == 0x15) {
cancelMeasurement();
return;
}
byte [] data = new byte [3];
long timeStart = System.currentTimeMillis();
this.timePassed = System.currentTimeMillis() - timeStart;
while ((this.timePassed < (this.time))&&(this.finished)) {
try {
in.read(data);
processData(data);
Thread.sleep(1000);
this.timePassed = System.currentTimeMillis() - timeStart;
} catch (Exception e) {
e.printStackTrace();
}
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please remember to close your Input/output streams first, then close the socket.
By closing the streams, you kick off the disconnect process. After you close the socket, the connection should be fully broken down.
If you close the socket before the streams, you may be bypassing certain shutdown steps, such as the (proper) closing of the physical layer connection.
Here's the method I use when its time to breakdown the connection.
/**
* Reset input and output streams and make sure socket is closed.
* This method will be used during shutdown() to ensure that the connection is properly closed during a shutdown.
* #return
*/
private void resetConnection() {
if (mBTInputStream != null) {
try {mBTInputStream.close();} catch (Exception e) {}
mBTInputStream = null;
}
if (mBTOutputStream != null) {
try {mBTOutputStream.close();} catch (Exception e) {}
mBTOutputStream = null;
}
if (mBTSocket != null) {
try {mBTSocket.close();} catch (Exception e) {}
mBTSocket = null;
}
}
EDIT: Adding code for connect():
// bluetooth adapter which provides access to bluetooth functionality.
BluetoothAdapter mBTAdapter = null;
// socket represents the open connection.
BluetoothSocket mBTSocket = null;
// device represents the peer
BluetoothDevice mBTDevice = null;
// streams
InputStream mBTInputStream = null;
OutputStream mBTOutputStream = null;
static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
/**
* Try to establish a connection with the peer.
* This method runs synchronously and blocks for one or more seconds while it does its thing
* SO CALL IT FROM A NON-UI THREAD!
* #return - returns true if the connection has been established and is ready for use. False otherwise.
*/
private boolean connect() {
// Reset all streams and socket.
resetConnection();
// make sure peer is defined as a valid device based on their MAC. If not then do it.
if (mBTDevice == null)
mBTDevice = mBTAdapter.getRemoteDevice(mPeerMAC);
// Make an RFCOMM binding.
try {mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
} catch (Exception e1) {
msg ("connect(): Failed to bind to RFCOMM by UUID. msg=" + e1.getMessage());
return false;
}
msg ("connect(): Trying to connect.");
try {
mBTSocket.connect();
} catch (Exception e) {
msg ("connect(): Exception thrown during connect: " + e.getMessage());
return false;
}
msg ("connect(): CONNECTED!");
try {
mBTOutputStream = mBTSocket.getOutputStream();
mBTInputStream = mBTSocket.getInputStream();
} catch (Exception e) {
msg ("connect(): Error attaching i/o streams to socket. msg=" + e.getMessage());
return false;
}
return true;
}
I found that if I call socket.close() too soon after a recent communication via the OutputStream, then the close fails and I cannot reconnect. I added a Thread.sleep(1000) just prior to the call to close() and this seems to solve it.
HI,
I've seen the exact same problem (HTC Desire).
Despite closing the socket by the book (as Brad suggests), the next connect() blocks forever - until ended by close() by another thread.
I circumvented the problem by always calling BluetoothAdapter.disable()/.enable() before connecting. Awful, unfriendly hack, I know...
I suspect that some of the present BT issues are manufacturer specific, as some app implementors seem to live happily with createRfcommSocketToServiceRecord(), which definitely fails on my HTC Desire (Android 2.1 update 1).
I have seen indications (sorry, don't have references) that HTC Desire's BT stack differs from the Nexus One, although they seem to be very similar devices...
BR
Per
(addition)
Here's a very simple activity to reproduce the problem (without my disable/enable 'cure'):
package com.care2wear.BtTest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class BtTestActivity extends Activity {
private static final String TAG="BtTest";
BluetoothAdapter mBtAdapter = null;
BluetoothDevice mBtDev = null;
BluetoothSocket mBtSocket = null;
InputStream isBt;
OutputStream osBt;
String mAddress = "00:18:E4:1C:A4:66";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
connect(); // ok
disconnect(); // ok
connect(); // this invariably fails - blocked until BT is switched off by someone else, or the peer device turns off/goes out of range
disconnect();
}
private void init() {
Log.d(TAG, "initializing");
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
mBtDev = mBtAdapter.getRemoteDevice(mAddress);
Log.d(TAG, "initialized");
}
private void connect() {
try {
Log.d(TAG, "connecting");
Method m = mBtDev.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
mBtSocket = (BluetoothSocket) m.invoke(mBtDev, 1);
mBtSocket.connect();
Log.d(TAG, "connected");
} catch (SecurityException e) {
Log.e(TAG, "SecEx", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "NsmEx", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "IArgEx", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "IAccEx", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "ItEx", e);
} catch (IOException e) {
Log.e(TAG, "IOEx", e);
}
}
private void disconnect() {
Log.d(TAG, "closing");
if (isBt != null) {
try {
isBt.close();
} catch (IOException e) {
Log.e(TAG, "isBt IOE", e);
}
isBt = null;
}
if (osBt != null) {
try {
osBt.close();
} catch (IOException e) {
Log.e(TAG, "osBt IOE", e);
}
osBt = null;
}
if (mBtSocket != null) {
try {
mBtSocket.close();
} catch (IOException e) {
Log.e(TAG, "socket IOE", e);
}
mBtSocket = null;
}
Log.d(TAG, "closed");
}
}
If anyone can spot if I'm doing it wrongly, feel free to comment :)
(addition 2)
I think I got it to work now:
The official method of connecting RFCOMM (via SDP) now actually seems to work (HTC Desire, 2.1 update 1), BUT I had to remove and re-pair the BT device. Go figure..
Reconnection may still fail (service discovery failure) if I reconnect 'too quickly' (quit app, then immediately restart). Guess the connection is not completely down yet..
If I always end the (last) activity not only with finish(), but also with Runtime.getRuntime().exit(0);, it works a lot better. Go figure again...
If anyone can explain this, I'll happily learn.
/Per
(addition 3)
Finally got the Froyo (2.2) update for my Desire, and as far as I can see, SPP now works :)
/Per
I was developing an app that conects to a BT device. Your code works fine in my HTC Wildfire but with a Samsung Galaxy I5700 doen't work. Both os are 2.1 update but.....
The exception was 'InvocationTargetException'
The only thing I had to modify is the disconnect().
private void disconnect() {
if(Conectado){
try {
***mBtSocket.close();***
texto.setText(texto.getText()+"\nDesconectado");
Conectado = false;
} catch (IOException e1) {
// TODO Auto-generated catch block
texto.setText(texto.getText()+"\n"+e1.getMessage());
}
catch (Exception e2) {
// TODO Auto-generated catch block
texto.setText(texto.getText()+"\n"+e2.getMessage());
}
}
Hey so I have been using the Bluetooth Chat application from The Android Development site and they provide a stop() method in BluetoothChatService class. So I simply created an instance of it in my main class and and called the stop function from my disconnect button.
Here is how I call it in my main class
// Member object for the chat services
private BluetoothManager mChatService = null;
case R.id.disconnect:
mChatService.stop();
break;
The stop() method in BluetoothChatService
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
public synchronized void stop()
{
if (mConnectThread != null)
{
mConnectThread.cancel(); mConnectThread = null;
}
if (mConnectedThread != null)
{
mConnectedThread.cancel(); mConnectedThread = null;
}
if (mAcceptThread != null)
{
mAcceptThread.cancel(); mAcceptThread = null;
}
}
I have the same Issue.
This is the trouble with the Bluetooth Module CSR BC417, present in many devices as serial to bluetooth adapter with SPP profile.
With another Bluetooth module android device works well, and the bluetooth release the conection after the socket is closed,
but with devices with this CSR core not.
Tested on SPP Bluetooth to Serial Adaptor based on CSR BC417, and Bluetooth module from Actisys.
Both with Android 4.0 devices.
I dont know why but is a compatibility issue between harwares, try to change the serial adaptor for another with a different Core.
I tryout programatically to find a solution, even disabling a bluetooth, but is impossible, the trouble is originated on the CSR module.