unable to connect bluetooth device - android

I am trying to connect bluetooth device and want to send data to that device and also want to receive data from that device.
To achieve this I follow android developer bluetooth document but seems I unable to connect another device because while connecting it's throwing following exception.
09-13 13:27:56.913: I/BluetoothConnect(2980): Connect exception:-java.io.IOException: [JSR82] connect: Connection is not created (failed or aborted).
Steps which I follow.
Enabling Bluetooth
Intent turnOnIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Getting Bluetooth Paired Device
Set<BluetoothDevice> bondSet = myBluetoothAdapter.getBondedDevices();
ArrayList<HashMap<String, String>> bondedhDevicesList = new ArrayList<HashMap<String, String>>();
for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) {
BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", bluetoothDevice.getName());
map.put("address", bluetoothDevice.getAddress());
bondedhDevicesList.add(map);
}
Getting UUID of device
bluetoothDevice =
myBluetoothAdapter.getRemoteDevice(address);
// min api 15 !!!
Method m;
try {
m = bluetoothDevice.getClass().
getMethod("fetchUuidsWithSdp", (Class[]) null);
m.invoke(bluetoothDevice, (Object[]) null );
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connecting to device
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
public ConnectThread(BluetoothDevice device, String uuid, BluetoothAdapter mBluetoothAdapter) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
this.mBluetoothAdapter = mBluetoothAdapter;
mmDevice = device;
Method m;
try {
mBluetoothAdapter.cancelDiscovery();
mmSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(device, 1);
} catch (IOException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
// TODO Auto-generated catch block
Log.i("BluetoothConnect", e.toString());
e.printStackTrace();
}
//mBluetoothAdapter.cancelDiscovery();
//socket.connect();
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Constants.globalSocket = mmSocket;
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
Log.i("BluetoothConnect", "Connect exception:-"+connectException.toString());
try {
mmSocket.close();
} catch (IOException closeException) {
Log.i("BluetoothConnect", "close exception:-"+closeException.toString());
}
return;
}
}
But while connecting then i am getting that exception.
5. Writing to device.
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
CreatePacket.mHandler.obtainMessage(MESSAGE_READ , bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.i("ConnectedThread", "while receiving data:-"+e.toString());
break;
}
}
}
public void write(byte[] bytes) {
Log.i("ConnectedThread", "data while writing:-"+bytes.toString());
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.i("ConnectedThread", "while writing data to bluetooth:-"+e.toString());
}
}
If I still try to write then data then I am getting following exception.
Please give me any hint or reference.
09-13 13:48:55.079: I/ConnectedThread(2980): while writing data to bluetooth:-java.io.IOException: socket closed
I am stuck on this from last three day but still not getting any solution.

The best way is to refer the sample chat application provided by the Android. That has covered all necessary tasks like list out available devices, establish connection, send data and receive, etc. U can get that and refer.
https://android.googlesource.com/platform/development/+/eclair-passion-release/samples/BluetoothChat

Here is a sample code which I am using to connect to my Bluetooth module..
public class OpenBluetoothPort extends AsyncTask<String, Void, BluetoothSocket> {
private final UUID SPP_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter mBluetoothAdapter;
private OnBluetoothPortOpened mCallback;
private BluetoothSocket mBSocket;
public interface OnBluetoothPortOpened {
public void OnBluetoothConnectionSuccess(BluetoothSocket socket);
public void OnBluetoothConnectionFailed();
}
public OpenBluetoothPort(Context context, OnBluetoothPortOpened callback) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mCallback = callback;
}
#Override
protected BluetoothSocket doInBackground(String... params) {
if(mBluetoothAdapter.isEnabled()) {
try {
for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
if(bt.getName().equalsIgnoreCase(params[0])) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
mBluetoothAdapter.cancelDiscovery();
mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
mBSocket.connect();
return mBSocket;
}
}
} catch(IOException e) {
if(mBSocket != null) {
try {
mBSocket.close();
} catch (IOException e1) {
Log.i("Bluetooth Close Exception","Error in closing bluetooth in OpenBluetoothPort.class");
e1.printStackTrace();
}
mBSocket = null;
}
Log.i("Bluetooth Connect Exception","Error in connecting in OpenBluetoothPort.class");
e.printStackTrace();
return null;
}
}
return null;
}
#Override
protected void onPostExecute(BluetoothSocket result) {
super.onPostExecute(result);
if(result != null && result.isConnected()) {
mCallback.OnBluetoothConnectionSuccess(result);
} else {
mCallback.OnBluetoothConnectionFailed();
}
}
}

Related

Bluetooth connection doesn't close

hello everybody i have been working on this app for so long now, and i think i almost finished but there is a problem and i tried a lot of different ways to solve it but i couldn't so any help i would appreciate .
the app is simple Bluetooth data sender to an Bluetooth module and it works just fine the problem occur if i wanted to close the connection from the app i couldn't close it and i have tried interrupt and the cancel method and putting a condition in a while loop but without any luck so can anyone help me please thank you.
this is my client thread (the same as android developer)
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private boolean x;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
}
catch (IOException e) {
// Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
while (true) {
bluetoothAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) {
Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
// Do work to manage the connection (in a separate thread)
xHandler.obtainMessage(0, mmSocket).sendToTarget();
if(x==false){
break;
}
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
Log.i(tag,"cancel 1");
mmSocket.close();
x=false;
// mmDevice.close();
} catch (IOException e) { }
}
}
and this is my connected class
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean x;
//private FileInputStream fis;
private int s;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//s=x;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
// if (s == 1) {
byte[] buffer;
// buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs}
//}
while (x) {
try {
// Read from the InputStream
buffer=new byte[1024];
// buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
xHandler.obtainMessage(1, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
Log.i(tag,"write");
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
mmInStream.close();
mmOutStream.close();
x=false;
Log.i(tag,"cancel 2");
}
catch (IOException e) { }
}
}
and finally the handler:
public Handler xHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handleeer");
super.handleMessage(msg);
switch(msg.what){
case 0:
// DO something
// if(omar==1){
//(BluetoothSocket)msg.obj
// bluetoothSocket=(BluetoothSocket).msg.obj;
connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_LONG).show();
//omar++;}
//String s = "79";
String s="h";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case 1:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
break;
}
}
};

Android sending command via bluetooth failed

I am going to implement the module of sending commands from my Android tablet to electronic device embedded with Bluetooth IC-chips Andrino HC-06 , for configuration of my device via Bluetooth. When it comes to execution, it seems that there is no observable response from the device when sending 22 23 54 01 C8.
It show the following timeout exception
It is expected that the device will restart and return many messages. What should I know more about when sending these eta commands to my device for remote control ?
The log cat message
05-23 18:19:44.866: E/BluetoothChatService(512): java.io.IOException: bt socket closed, read return: -1
05-23 18:19:44.866: E/BluetoothChatService(512): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:429)
05-23 18:19:44.866: E/BluetoothChatService(512): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
05-23 18:19:44.866: E/BluetoothChatService(512): at java.io.InputStream.read(InputStream.java:162)
05-23 18:19:44.866: E/BluetoothChatService(512): at com.example.android.BluetoothChat.BluetoothChatService$ConnectedThread.run(BluetoothChatService.java:485)
The below is my code
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
.show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
Sending Commands
public void write(byte[] buffer) {
try {
boolean connected = false;
BluetoothSocket sock = null;
InputStream in = null ;
OutputStream out = null ;
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:14:01:12:28:12");
Method m = zee.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
sock = (BluetoothSocket) m.invoke(zee, Integer.valueOf(1));
sock.connect();
in = sock.getInputStream();
out = sock.getOutputStream();
char[] test = { 0x22 , 0x21 , 0x03 , 0x00 , 0xc9};
for(int k=0; k < test.length; k++){
new DataOutputStream(sock.getOutputStream()).writeByte(test[k]);
}
byte [] bfferX = new String(test).getBytes("UTF-8");*/
mmOutStream.write(buffer);
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I suppose the device are already paired and that the android device performs the discovery.
Why do you think it is a matter of timeout? The exception tells that the communication socket is already closed. Maybe you succeed in create a BluetoothSocket and close it "accidentally" (maybe, after flushing, you close the output or input stream related to the socket).
Since you are following the Android BluetoothChat example you should:
1) perform the discovery and listen for available devices:
private final BroadcastReceiver deviceFoundBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action) && mState==STATE_DISCOVERING) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
new ConnectThread(device).start();
}
}
};
2) connect to the device:
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = InsecureBluetooth.createRfcommSocketToServiceRecord(mmDevice, YOUR_UUID, false);
}
catch (IOException e) { }
mmSocket = tmp;
}
#Override
public void run() {
try {
btAdapter.cancelDiscovery(); // be sure discovery is cancelled
mmSocket.connect(); // blocking call, returns only on a successful connection or an exception
connected(mmSocket, mmSocket.getRemoteDevice());
new ConnectedThread(mmSocket, mmDevice.getAddress()).start(); // start connected thread
}
catch (IOException e) {}
}
public void cancel() {}
}
3) Retrieve the input and output stream for communicating with the paired device (do not close the streams while communication is needed):
private class ConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private String macAddress;
public ConnectedThread(BluetoothSocket socket, String macAddress) {
this.macAddress = macAddress;
this.mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
mmInStream = mmSocket.getInputStream();
mmOutStream = mmSocket.getOutputStream();
}
catch (IOException e) {}
}
#Override
public void run() {
// perform communication
}
}
The class InsecureBluetooth is used to "avoid" the pairing phase and is based on this Stanford peace of code:
#TargetApi(10)
public class InsecureBluetooth {
static private class InUse extends RuntimeException { }
public static BluetoothServerSocket listenUsingRfcommWithServiceRecord(BluetoothAdapter adapter, String name, UUID uuid, boolean encrypt) throws IOException {
if(Build.VERSION.SDK_INT<10) {
try {
Class c_rfcomm_channel_picker = null;
Class[] children = BluetoothAdapter.class.getDeclaredClasses();
for(Class c : children) {
Log.e("TO", "class " + c.getCanonicalName());
if(c.getCanonicalName().equals(BluetoothAdapter.class.getName() + ".RfcommChannelPicker")) {
c_rfcomm_channel_picker = c;
break;
}
}
if(c_rfcomm_channel_picker == null)
throw new RuntimeException("can't find the rfcomm channel picker class");
Constructor constructor = c_rfcomm_channel_picker.getDeclaredConstructor(UUID.class);
if(constructor == null)
throw new RuntimeException("can't find the constructor for rfcomm channel picker");
Object rfcomm_channel_picker = constructor.newInstance(new Object[] {uuid});
Method m_next_channel = c_rfcomm_channel_picker.getDeclaredMethod("nextChannel", new Class[] {});
m_next_channel.setAccessible(true);
BluetoothServerSocket socket = null;
int channel;
int errno;
while (true) {
channel = (Integer)m_next_channel.invoke(rfcomm_channel_picker, new Object[] {});
if (channel == -1) {
throw new IOException("No available channels");
}
try {
socket = listenUsingRfcomm(channel, encrypt);
break;
} catch(InUse e) {
continue;
}
}
Field f_internal_service = adapter.getClass().getDeclaredField("mService");
f_internal_service.setAccessible(true);
Object internal_service = f_internal_service.get(adapter);
Method m_add_rfcomm_service_record = internal_service.getClass().getDeclaredMethod("addRfcommServiceRecord", new Class[] {String.class, ParcelUuid.class, int.class, IBinder.class});
m_add_rfcomm_service_record.setAccessible(true);
int handle = (Integer)m_add_rfcomm_service_record.invoke(internal_service, new Object[] { name, new ParcelUuid(uuid), channel, new Binder() } );
if (handle == -1) {
try {
socket.close();
} catch (IOException e) {}
throw new IOException("Not able to register SDP record for " + name);
}
Field f_internal_handler = null;
try {
f_internal_handler = adapter.getClass().getDeclaredField("mServiceRecordHandler");
} catch(Exception e) {
f_internal_handler = adapter.getClass().getDeclaredField("mHandler");
}
f_internal_handler.setAccessible(true);
Object internal_handler = f_internal_handler.get(adapter);
Method m_set_close_handler = socket.getClass().getDeclaredMethod("setCloseHandler", new Class[] {Handler.class, int.class});
m_set_close_handler.setAccessible(true);
m_set_close_handler.invoke(socket, new Object[] { internal_handler, handle});
return socket;
} catch (Exception e) {}
}
else {
return adapter.listenUsingInsecureRfcommWithServiceRecord(name, uuid);
}
}
private static BluetoothServerSocket listenUsingRfcomm(int port, boolean encrypt, boolean reuse) throws IOException, InUse {
BluetoothServerSocket socket = null;
try {
Constructor<BluetoothServerSocket> constructor = BluetoothServerSocket.class.getDeclaredConstructor(int.class, boolean.class, boolean.class, int.class);
if(constructor == null)
throw new RuntimeException("can't find the constructor");
constructor.setAccessible(true);
Field f_rfcomm_type = BluetoothSocket.class.getDeclaredField("TYPE_RFCOMM");
f_rfcomm_type.setAccessible(true);
int rfcomm_type = (Integer)f_rfcomm_type.get(null);
Field f_e_addr_in_use = BluetoothSocket.class.getDeclaredField("EADDRINUSE");
f_e_addr_in_use.setAccessible(true);
int e_addr_in_use = (Integer)f_e_addr_in_use.get(null);
socket = constructor.newInstance(new Object[] { rfcomm_type, false, encrypt, port } );
Field f_internal_socket = socket.getClass().getDeclaredField("mSocket");
f_internal_socket.setAccessible(true);
Object internal_socket = f_internal_socket.get(socket);
Method m_bind_listen = internal_socket.getClass().getDeclaredMethod("bindListen", new Class[] {});
m_bind_listen.setAccessible(true);
Object result = m_bind_listen.invoke(internal_socket, new Object[] {});
int errno = (Integer)result;
if(reuse && errno == e_addr_in_use) {
throw new InUse();
} else if (errno != 0) {
try {
socket.close();
} catch (IOException e) {}
internal_socket.getClass().getMethod("throwErrnoNative", new Class[] {int.class}).invoke(internal_socket, new Object[] { errno });
}
return socket;
} catch (Exception e) {}
}
public static BluetoothServerSocket listenUsingRfcomm(int port, boolean encrypt) throws IOException {
return listenUsingRfcomm(port, encrypt, false);
}
private static BluetoothSocket createRfcommSocketToServiceRecord(BluetoothDevice device, int port, UUID uuid, boolean encrypt) throws IOException {
try {
BluetoothSocket socket = null;
Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor(
int.class, int.class, boolean.class, boolean.class, BluetoothDevice.class, int.class, ParcelUuid.class);
if(constructor == null)
throw new RuntimeException("can't find the constructor for socket");
constructor.setAccessible(true);
Field f_rfcomm_type = BluetoothSocket.class.getDeclaredField("TYPE_RFCOMM");
f_rfcomm_type.setAccessible(true);
int rfcomm_type = (Integer)f_rfcomm_type.get(null);
socket = constructor.newInstance(new Object[] { rfcomm_type, -1, false, true, device, port, uuid != null ? new ParcelUuid(uuid) : null} );
return socket;
} catch (Exception e) {}
}
public static BluetoothSocket createRfcommSocketToServiceRecord(BluetoothDevice device, UUID uuid, boolean encrypt) throws IOException{
if(Build.VERSION.SDK_INT<10) {
return createRfcommSocketToServiceRecord(device, -1, uuid, encrypt);
}
else {
return device.createInsecureRfcommSocketToServiceRecord(uuid);
}
}
public static BluetoothSocket createRfcommSocket(BluetoothDevice device, int port, boolean encrypt) throws IOException {
return createRfcommSocketToServiceRecord(device, port, null, encrypt);
}
}

Reading data via Motorola bluetooth barcode scanner (CS3070) is getting as two string?

I'm working in reading data via Motorola Bluetooth barcode scanner(CS3070).Actually, my original barcode data is : 1PCS3070-SR10007WW but i'm getting as two string example
1P as first string and CS3070-SR10007WW as second string. Getting as two string happen to all scanned barcode via reading through bluetooth. I hope now you may understand my problem. Same code as used from developer link
Here is my code of connecting and reading data in thread via bluetooth:
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG,
"unable to close() socket during connection failure",
e2);
}
// Start the service over to restart listening mode
BluetoothService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(ScanningActivity.MESSAGE_READ,
bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* #param buffer
* The bytes to write
*/
public void write(String buffer) {
try {
mmOutStream.write((buffer + "\n").getBytes());
// Share the sent message back to the UI Activity
mHandler.obtainMessage(ScanningActivity.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
mmInStream.close();
mmOutStream.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
Let me know if anybody have answer for it. Thanks in advance

android bluetooth file not transferring

public class ConnectThread extends Thread
{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final OutputStream mmOutStream;
private UUID uuid = UUID.randomUUID();
private byte[] temp;
public ConnectThread(BluetoothDevice device,byte[] temp)
{
BluetoothSocket socket = null;
OutputStream tmpOut = null;
mmDevice = device;
this.temp = temp;
try
{
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
tmpOut = socket.getOutputStream();
}
catch (Exception e) { }
mmSocket = socket;
mmOutStream = tmpOut;
}
public void run()
{ enter code here
try
{
mmSocket.connect();
write(temp);
}
catch (IOException connectException)
{
try
{
mmSocket.close();
}
catch (IOException closeException)
{ }
return;
}
}
public void write(byte[] bytes)
{
try
{
mmOutStream.write(bytes);
mmOutStream.flush();
mmOutStream.close();
}
catch (IOException e) { }
}
public void cancel()
{
try
{
mmSocket.close();
}
catch (IOException e) { }
}
}
I am trying to transfer a txt file to another device. I am passing the bluetooth device and message(in bytes) to this class and starting the thread form main activity. After scanning, the devices displaying and pairing is also working. I am not getting any exception in the code. But I am not receiving a file.
Why I am not receiving a file on other mobile?
Can somebody help me please.
Thanks, Faraz

Bluetooth insecure connection act like a loopback?

I'm developing an Android Bluetooth app that aim to speak using Bluetooth with a device we created, I successfully made everything work on most device on Android 3+ but it seems that android 2.3.x (which is our minimal requirement) doesn't act like the others. I also reproduced the same behavior on a Huawei Ascend P1.
What happens is that on Android side everything acts normal, I connect to the device and a pairing request is made if I'm not paired, I retrieve both in and outstream but when I use them they act like I'm speaking to myself on a loopback. Everything written on the outputstream is read on the inputstream. And of course the device does not see anything (It seems that it doesn't even know that an android phone is connected).
Here are some code sample from my sources (most of it is exactly as described in the android documentation):
Connection thread:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
btSpeaking = true;
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
tmp = device.createInsecureRfcommSocketToServiceRecord(BluetoothUuid.declareUuid.getUuid());
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mConnected = new ConnectedThread(mmSocket);
mConnected.start();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Read thread:
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
WSLog.e(tag, e.getMessage(), e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
try {
writeSocket(RESET, empty);
} catch (IOException e1) {
return;
}
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
for (int size = 0; size < framesize;) {
int read = mmInStream.read(frame, size, frame.length - size);
if (read < 0) {
return;
}
size = size + read;
}
} catch (IOException e) {
return;
}
}
}
Write socket:
private void writeSocket(byte comm, byte[] data) throws IOException {
ByteBuffer bf = ByteBuffer.allocate(1 + data.length);
bf.put(PROTO);
bf.put(comm);
bf.put(data);
mmOutStream.write(bf.array());
}
I really hope I'm not doing something obviously wrong but as I can't get why it doesn't work I had no choice but to ask for help.
Thanks,
Martin

Categories

Resources