Connecting Bluetooth in Android - android

I have done a simple app to connect my phone with an Arduino via BT and all goes right. My phone have Android 2.3.6... But, when I try the app on my tablet (with android 4.0.3), I can't connect. I post here the specific piece of code:
try {
BluetoothSocket socket = mydevice.createRfcommSocketToServiceRecord(UUID.fromString(ARDUINO_STANDAR_UUID));
socket.connect();
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
Log.d(TAG, "Connected");
}
catch (IOException e) { Log.e(TAG, e.getMessage()); }
}
Using the Log, the problem is at socket.connect(); at that point, I have to enter the PIN of the device, but it don't connect anyway... The error is "Connection refused"...
What can be wrong?

Try something like this to take care of the connection. I just updated an old android-10 app the other day to android-17 and dealt with exactly this.
BluetoothDevice yourDevice;
try {
Method m = yourDevice.getClass().getMethod( "createInsecureRfcommSocket", new Class[] { int.class } );
selectedDeviceSocket = (BluetoothSocket) m.invoke( yourDevice, Integer.valueOf( 1 ) );
selectedDeviceSocket.connect();
}

Related

Bluetooth communication b/w Android and IOT device

I am trying to establish Bluetooth communication between Android and IOT (intel galileo) device.
The code at IOT side (i am keeping it as a client), it will send data to android, but here one port number is hard coded. This is in python.
def record_transmit_to_subscriber(self, subscriber, message):
server_addr = subscriber
port = 6
client_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
client_socket.connect((server_addr, port))
client_socket.send(message)
client_socket.close()
return True
except Exception as e:
print "Unable to make connection with subscriber", subscriber
return False
Now at android (server) side:
private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
BluetoothServerSocket tmp = null;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
// MY_UUID is the applications UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
GlobalUtils.writeLogFile("Error in BLE Listening " + e.getMessage());
}
mmServerSocket = tmp;
} catch (Exception e){
GlobalUtils.writeLogFile("Exception in Accept Thread " + e.getMessage());
}
I do believe there in some problem in this code, at client side it is using port number while at server side it is using uuid. can someone please rectify how to modify this code to make connection work.
Seems You forgot to create socket and streams:
try {
BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("<MAC_address_of_your_device>");
mSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
mSocket.connect();
} catch (IOException e) {
Log.e(TAG, "Fail connect");
}
// Get the input and output streams for BT socket
try {
inStream = mSocket.getInputStream();
outStream = mSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Fail to open socket streams");
}
Than You can create Thread for read data from inStream (for example inStream.read(<data_buffer>); and Thread for write data to outStream (for example outStream.write(<data_buffer>); outStream.flush();).

Android bluethoot with printer adapter

I have problem.
i have one bluethoot printer adapter "Bluetake BT220" and one printer "Star DP8340S".
i want connect my bluetot bt220 to my app android , i have others connections to zebra printers but implemented the connection.
for this adapter bluethoot, have not connection, looking much the net, I saw that I can connect directly bluethoot.
I can connect to the device but I'm not able to print in the
someone could tell me where I can start?any suggestion is welcome.
any documentation, do not hesitate to ask
thank you all, by make life easier.
I answer to myself.
solved : I've just created a Connection bluethoot follows
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice bluetakebt220 = bluetoothAdapter.getRemoteDevice(obj.getMac().toString());
Method m;
BluetoothSocket mBTsocket= null;
m = bluetakebt220.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
// mBTsocket = (BluetoothSocket) m.invoke(bluetakebt220, 1);
UUID num = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mBTsocket = bluetakebt220.createRfcommSocketToServiceRecord(num);
mBTsocket.connect();
and now just need to print
String txt ="LINE 1 \n LINE 2 \n";
byte[] CPCLFormat = null;
try {
CPCLFormat = txt .getBytes("utf-8");
try {
os.write(CPCLFormat);
} catch (Exception e) {
os.close();
e.printStackTrace();
}
} catch (UnsupportedEncodingException e1) {
CPCLFormat = null;
os.close();
e1.printStackTrace();
}
os.close();
I hope that helps, thanks

Android Serversocket does not seem to accept connections on emulators

I've been trying to implement a simple socket communication between two Android emulators but just can't seem to get it.
My server:
public void run() {
if (SERVERIP != null) {
try {
serverStatus.setText("My IP: " + SERVERIP);
serverSocket = new ServerSocket(6798);
serverStatus.setText("ServerSocket Created");
}
catch(Exception e) {
e.printStackTrace();
}
try {
while (true) {
serverStatus.setText("waiting for client");
Socket client = serverSocket.accept();
serverStatus.setText("Connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = in.readLine();
serverStatus.setText(line);
in.close();
client.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
else
serverStatus.setText("Couldn't detect internet connection.");
}
My Client:
try {
InetAddress ina = InetAddress.getByName("10.0.2.2");
socket = new Socket(ina, 6789);
}
catch (Exception e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Hey Server!");
dispText.setText("sent");
}
catch (Exception e) {
e.printStackTrace();
}
The Client side goes on to display the message "sent" however the Server does not move beyond "waiting for client" (stuck on the blocking accept()).
I've used telnet on my Windows machine to redirect port 6789 to 6798 on the server emulator's console. I've also tried turning off my firewall and the other suggestions posted on the similar questions asked here. Please help as just can't seem to get it and feel like I'm making a very stupid mistake.
Also, can anyone please tell me how it is possible for the Client to move beyond the Socket creation code line if the Server is still stuck on accept(). Or, does it not matter to the client that the Server isn't responding as long as it is listening on the port??
Android emulators are placed behind a virtual firewall/router by design, and cannot see each other, even when they are on the same network. The "Using Network Redirection", as well as "Interconnecting Emulator Instances" part of Google's doc on the emulator explains how to communicate with an emulator instance.
As for your last question. Use the empty constructor for socket, and then use the connect call with a specified timeout.

Android 4.0+ Bluetooth connection error to an embedded device: "Permission Denied"

I have the following setup:
An Android device uses a 'Client' socket to connect to a remote embedded device, The Android application uses the following code snippet to connect to the embedded device.
On the embedded device uses MindTree BT stack, where server serial socket is prepared according to some properties in the device, which the Android application is familiar with, the connection defined on the embedded device, is not secured!!
The combination of both applications works on:
2 LG phones different models (version code < 10 uses the "Normal method")
2 HTC's different models (version code < 10 uses the "Workaround method")
Pantech Tablet (version code < 13 uses the "Workaround method")
Today, I've tried the application on Samsung S3, Motorola MB886, and a Nexus 7...
All resulted in a "Permission Denied" when calling to socket.connect()... (I have the proper permissions in the manifest, otherwise it would not work on the other devices.)
All the new devices I've tested on are version code > 4.0, so I'm wondering:
Does anyone know about any changes in the API?
Perhaps Android 4.0+ forces security?
It seem that the error occur in the Bonding state, since I can see on the embedded program logs...
Any insights?
The code:
public final synchronized int connectToDevice(int connectingMethod)
throws BluetoohConnectionException {
if (socket != null)
throw new BadImplementationException("Error socket is not null!!");
connecting = true;
logInfo("+---+ Connecting to device...");
try {
lastException = null;
lastPacket = null;
if (connectingMethod == BluetoothModule.BT_StandardConnection
|| connectingMethod == BluetoothModule.BT_ConnectionTBD)
try {
socket = fetchBT_Socket_Normal();
connectToSocket(socket);
listenForIncomingSPP_Packets();
onConnetionEstablished();
return BluetoothModule.BT_StandardConnection;
} catch (BluetoohConnectionException e) {
socket = null;
if (connectingMethod == BluetoothModule.BT_StandardConnection) {
throw e;
}
logWarning("Error creating socket!", e);
}
if (connectingMethod == BluetoothModule.BT_ReflectiveConnection
|| connectingMethod == BluetoothModule.BT_ConnectionTBD)
try {
socket = fetchBT_Socket_Reflection(1);
connectToSocket(socket);
listenForIncomingSPP_Packets();
onConnetionEstablished();
return BluetoothModule.BT_ReflectiveConnection;
} catch (BluetoohConnectionException e) {
socket = null;
if (connectingMethod == BluetoothModule.BT_ReflectiveConnection) {
throw e;
}
logWarning("Error creating socket!", e);
}
throw new BluetoohConnectionException("Error creating RFcomm socket for BT Device:" + this
+ "\n BAD connectingMethod==" + connectingMethod);
} finally {
connecting = false;
}
}
protected void onConnetionEstablished() {
logInfo("+---+ Connection established");
}
private synchronized void listenForIncomingSPP_Packets() {
if (socketListeningThread != null)
throw new BadImplementationException("Already lisening on Socket for BT Device" + this);
logInfo("+---+ Listening for incoming packets");
socketListeningThread = new Thread(socketListener, "Packet Listener - " + bluetoothDevice.getName());
socketListeningThread.start();
}
private BluetoothSocket fetchBT_Socket_Normal()
throws BluetoohConnectionException {
try {
logInfo("+---+ Fetching BT RFcomm Socket standard for UUID: " + uuid + "...");
return bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
} catch (Exception e) {
throw new BluetoohConnectionException("Error Fetching BT RFcomm Socket!", e);
}
}
private BluetoothSocket fetchBT_Socket_Reflection(int connectionIndex)
throws BluetoohConnectionException {
Method m;
try {
logInfo("+---+ Fetching BT RFcomm Socket workaround index " + connectionIndex + "...");
m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
return (BluetoothSocket) m.invoke(bluetoothDevice, connectionIndex);
} catch (Exception e) {
throw new BluetoohConnectionException("Error Fetching BT RFcomm Socket!", e);
}
}
private void connectToSocket(BluetoothSocket socket)
throws BluetoohConnectionException {
try {
logInfo("+---+ Connecting to socket...");
socket.connect();
logInfo("+---+ Connected to socket");
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
logError("Error while closing socket", e1);
} finally {
socket = null;
}
throw new BluetoohConnectionException("Error connecting to socket with Device" + this, e);
}
}
After very long long time of investigating the matter I've found one reason for the error... on some Android devices the auto Bluetooth peering is not enabled/allowed.
So, apparently except for two connection method, there are also two Bluetooth adapter enabling method, one would be to throw an intent to ask the system to turn the adapter on, and the other is to call onto the BluetoothAdapter.enable() method, which enables the Bluetooth silently.
The first method, pops a confirmation dialog, and require user interaction while the other does not, and while not showing the Bluetooth enabling confirmation dialog, also the peering confirmation is not shown, which causes the connection error.
Using the first adapter enabling method solves the problem on most of the devices, like the Nexus 7, Samsung S3, and a few others, but on some devices there is still an issue, and I'm not really sure why, but this is much better since many devices are now working with the new implementation.

Bluetoothsocket timeout on read and write

I'm designin an application in Android that connects the mobile to a bluetooth device. I can do this, as I open a BluetoothSocket like this:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
Where device is the paired device with the mobile bluetooth desired. The thing is, this external device is a bit special, and it has different times for writing and answering to the mobile, so I need to put some timeouts on my socket for reading and writing, but I've searched a lot and it seems like BluetoothSocket doesn't support this.
Can anybody tell me a different way to admin timeouts on reading and writing to the port on the BluetoothSocket class for Android?
Thank you!
There are many Exceptions a socket or it's streams can throw. The socket.connect() for example can throw a ConnectTimeoutException. Every method in the BluetoothSocket context can through an IOException just take a look at the documentation and you will see which exception you have to catch in order to make your program work properly.
Here is the code for reading and writing code:
Writng code on port:
try
{
// Enviamos los bytes
DataOutputStream dOut = null;
dOut = new DataOutputStream(socket.getOutputStream());
// Send message
dOut.writeBytes(res);
dOut.flush();
}
catch (IOException e)
{
Dialogs.showErrorDialog("Error al recuperar la fecha y hora del dispositivo Nonin.", this);
}
Then, reading from port until response available:
DataInputStream dIn = null;
// We receive the answer
try
{
dIn = new DataInputStream(socket.getInputStream());
}
catch (IOException e)
{
Dialogs.showAlertDialog("An exception occured during bluetooth io stream creation", this);
}
while (true)
{
try
{
String data = dIn.readLine(); // readLine();
byte[] total = EncodingUtils.getBytes(data, "ASCII");
Dialogs.showInfoDialog("Mensaje ok: " + data.toString(), this);
}
catch (IOException e)
{
break;
}
}
The thing is that I think the writing works, as I convert the desired string into bytes, and it works. But then, when I'm waiting for response, it mixes further responses with the desired, and I think this is because timings.
There's no more code in the middle related with sockets. First, I create it. Then, I try to send a byte String. Then I wait until I receive the answer for the byte String that I just sent.
Thank you in advance.

Categories

Resources