My bluetooth connection unexpectedly closed in Android - android

java.io.IOException: bt socket closed, read return: -1
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:434)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.InputStreamReader.read(InputStreamReader.java:231)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.readLine(BufferedReader.java:397)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at com.example.lg.scoreboardapp.MainActivity$ConnectThread.run(MainActivity.java:336)
Sometimes in my app, client unexpectedly closed.
I don't know why......
I have three diveces. one devices is server. others are client.
They are connected well, but one client was closed. other client is still open.
Please give me the solution...!!
It's MainActivitity.. 336Lineenter code here
while(socket != null){
i++;
Log.d("MAinActivity","-----------------"+i+"-----------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str1 = in.readLine(); //<<---Line 336
Log.d("MainActivity","--------------------------------------"+str1+i);
json1 = str1;
parse();
}
It's ConnectThread client
private class ConnectThread extends Thread {
private BluetoothSocket socket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(MainActivity.this, "연결에 실패하였습니다.\n다시 시도하여 주세요", Toast.LENGTH_SHORT).show();
e.printStackTrace();
//mkmsg("Client connection failed: "+e.getMessage().toString()+"\n");
}
socket = tmp;
}
public void run() {
// mkmsg("Client running\n");
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
//mkmsg("Connect failed\n");
e.printStackTrace();
try {
socket.close();
socket = null;
} catch (IOException e2) {
//mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
socket = null;
e2.printStackTrace();
}
// Start the service over to restart listening mode
}
// If a connection was accepted
if (socket != null) {
//mkmsg("Connection made\n");
//mkmsg("Remote device address: "+socket.getRemoteDevice().getAddress().toString()+"\n");
//Note this is copied from the TCPdemo code.
try {
int i=0;
while(socket != null){
i++;
Log.d("MAinActivity","-----------------"+i+"-----------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str1 = in.readLine();
Log.d("MainActivity","--------------------------------------"+str1+i);
json1 = str1;
parse();
}
Log.d("MainActivity_341Line","socket is null.......... check this");
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"MainActivity_341Line socket is null.......... check this",Toast.LENGTH_LONG);
}
});
} catch(Exception e) {
//mkmsg("Error happened sending/receiving\n");
e.printStackTrace();
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error happened sending/receiving\\n",Toast.LENGTH_LONG);
Log.d("MainActivity_341Line","Error happened sending/receiving");
}
});
try {
socket.close();
socket = null;
} catch (IOException e2) {
//mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
socket = null;
Log.d("MainActivity_341Line","Error happened "+e2);
e2.printStackTrace();
}
}
} else {
//mkmsg("Made connection, but socket is null\n");
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Made connection, but socket is null\\n",Toast.LENGTH_LONG);
}
});
}
}
public void cancel() {
try {
socket.close();
Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}

Try to replace your run() method in your ConnectThread to this:
public void run()
{
Log.e(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
mAdapter.cancelDiscovery();
try
{
mmSocket.connect();
}
catch (IOException e)
{
try
{
Log.e(TAG,"Trying fallback...");
mmSocket = (BluetoothSocket)
mmDevice.getClass()
.getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice, 2);
mmSocket.connect();
Log.e(TAG,"Connected");
}
catch (Exception e2)
{
Log.e(TAG, "Couldn't establish Bluetooth connection!");
try
{
mmSocket.close();
}
catch (IOException e3)
{
Log.e(TAG, "unable to close() " + " socket during connection failure", e3);
}
connectionFailed();
return;
}
}
synchronized (BluetoothHelper.this)
{
mConnectThread = null;
}
connected(mmSocket, mmDevice);
}

Related

Bluetooth socket connect failed for Android 5.1

I want to receive data from a hardware device through Bluetooth in Android 5.1, but I got the following errors:
W/System.err: java.io.IOException: bt socket connect failed
W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:317)
W/System.err: at com.pda.bt.ConnectThread.run(ConnectThread.java:54)
E/error: bt socket connect failed
It just shows the error of bt socket connect failed. I tried to resolve the problem with various methods, but didn't work.
This is my code for connect:
public class ConnectThread extends Thread {
private final BluetoothAdapter mAdapter;
private final BluetoothDevice mDevice;
private final BluetoothSocket mySocket;
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device, BluetoothAdapter adapter) {
int sdk = Build.VERSION.SDK_INT;
BluetoothSocket _mySocket = null;
if (sdk >= 10) {
try {
_mySocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("error", "Error creating socket");
}
} else {
try {
_mySocket = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("error", "Error creating socket");
}
}
mDevice = device;
mAdapter = adapter;
mySocket = _mySocket;
Log.e("info", "=====>"+mDevice.getName());
Log.e("info", "=====>"+mDevice.getUuids());
}
public void run() {
mAdapter.cancelDiscovery();
try {
mySocket.connect();
} catch (IOException e) {
e.printStackTrace();
Log.e("error", e.getLocalizedMessage());
try {
mySocket.close();
} catch (Exception ee) {
Log.e("error", ee.getMessage());
}
}
}
public void cancel () {
try {
mySocket.close();
} catch (IOException e) {
Log.e("error", e.getMessage());
}
}
}

Android insecure bluetooth connection

I want to connect android mobile to one electronic device,but I want to connect it insecurely.but its giving me the error of "java.io.IOException: read failed, socket might closed or timeout, read ret: -1"
here is my code
package net.londatiga.android.bluetooth;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final UUID WELL_KNOWN_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,because
// mmSocket is final
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// tmp = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
tmp = device
.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
Object[] params = new Object[] {Integer.valueOf(1)};
// This is the trick
Method m = device.getClass().getMethod("createInsecureRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, params);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
#SuppressLint("NewApi")
public void run() {
// DebugLog.i(TAG, "Trying to connect...");
// Cancel discovery because it will slow down the connection
MainActivity.mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
boolean val=mmSocket.isConnected();
Log.v("val", ""+val);
// DebugLog.i(TAG, "Connection stablished");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
// DebugLog.e(TAG, "Fail to connect!", connectException);
try {
mmSocket.close();
} catch (IOException closeException) {
// DebugLog.e(TAG, "Fail to close connection", closeException);
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
You have to implement an another thread, like below, which always receives your calls and does operations. Start this thread when you start the application.
class AcceptThread extends
Thread {
private final BluetoothServerSocket serverSocket;
private boolean flag = true;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter
.listenUsingInsecureRfcommWithServiceRecord(
NAME_UUID, uuid);
} catch (IOException e) {
}
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = serverSocket.accept();
if (socket.isConnected()) {
Log.d(TAG, "run: connection successfull");
Log.d(TAG, "run: " + socket.getRemoteDevice().getName() + " " +
socket.getRemoteDevice().getAddress());
}
} catch (IOException e) {
try {
socket.close();
} catch (Exception eee) {
Log.d(TAG, "run: " + eee.getMessage());
}
break;
}
}
}
public void cancel() {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}

client Windows and Android server over USB

I'm making an Android App to communicate with a computer windows.
I found that it must be easy to do that by forwarding the port with ADB commands.
So i try to make a client/server connection over USB but i have some problems
my server on Windows:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("EchoClient.main()");
Socket client = null;
// initialize server socket
try {
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT * 1000);
// attempt to accept a connection
client = server.accept();
Globals.socketOut = new PrintStream(client.getOutputStream());
Globals.socketIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
// Globals.socketIn.YY
} catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus = "Connection has timed out! Please try again";
System.out.println(connectionStatus);
} catch (IOException e) {
System.out.println("error"+ e);
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
System.out.println("Cannot close server socket"+ ec);
}
}
if (client != null) {
System.out.println("connected");
}
}
public static class Globals {
private static String typeOfTransmission ;
static PrintStream socketOut = null;
static BufferedReader socketIn = null;
public static synchronized String getTypeTransmission(){
return typeOfTransmission;
}
public static synchronized void setTypeTransmission(String s){
typeOfTransmission = s;
}
}
}
android APP client
private Runnable initializeConnection = new Thread() {
public void run() {
Socket client = null;
// initialize server socket
try {
Log.d("ip",getLocalIpAddress());
client = new Socket(getLocalIpAddress(), 38300);
Globals.socketIn = new Scanner(new InputStreamReader(
client.getInputStream()));
Globals.socketOut = new PrintWriter(client.getOutputStream());
// Globals.socketIn.YY
} catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus = "Connection has timed out! Please try again";
mHandler.post(showConnectionStatus);
} catch (IOException e) {
Log.e(TAG, "" + e);
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
Log.e(TAG, "Cannot close server socket"+ ec);
}
}
if (client != null) {
Globals.connected = true;
// print out success
connectionStatus = "Connection was succesful!";
Log.d(TAG, "connected!");
mHandler.post(showConnectionStatus);
while (Globals.socketIn.hasNext()) {
socketData = Globals.socketIn.next();
mHandler.post(socketStatus);
}
}
}
};
public String getLocalIpAddress(){
try{
for(Enumeration<NetworkInterface> en =NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for(Enumeration<InetAddress> enumIpAddress= intf.getInetAddresses();enumIpAddress.hasMoreElements();){
InetAddress inetAddress = enumIpAddress.nextElement();
if (!inetAddress.isLoopbackAddress()){
return inetAddress.getHostAddress().toString();
}
}
}
}catch(SocketException ex){
Log.e("ServerActivity",ex.toString());
}
return null;
}
Logger
01-29 11:43:49.640: D/ip(2981): fe80::a806:ff:fec6:d3d%p2p0
01-29 11:43:49.650: E/Connection(2981): java.net.ConnectException: failed to connect to /fe80::a806:ff:fec6:d3d%p2p0%4 (port 38300): connect failed: ECONNREFUSED (Connection refused)
thank you

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

Sending data over bluetooth via SPP using an android device

I'm trying to send data from an android device to a remote bluetooth device supporting Serial Port Profile(SPP). I notice whenever I open and close a socket after each press of a button, it is too slow. What socket commands should be executed in the Run() and Onclick() functions? The following is a class which does Bluetooth IO:
public class Selecteddevice extends Activity implements OnClickListener {
private static final String TAG = "THINBTCLIENT";
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice device;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.selecteddevice);
findViewById(R.id.toggleButton1).setOnClickListener(this);
findViewById(R.id.toggleButton2).setOnClickListener(this);
findViewById(R.id.toggleButton3).setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
String address = getIntent().getStringExtra("address");
TextView tv1 = (TextView) findViewById(R.id.textView_address);
tv1.setText(" DEVICE ADDRESS: " + address);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
device = mBluetoothAdapter.getRemoteDevice(address);
run();
}
public void run(){
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e)
{
Log.e(TAG, "ON START: Socket creation failed.", e);
}
try {
btSocket.connect();
} catch (IOException e)
{
Log.e(TAG, "sendTestByte: Socket connection failed.", e);
}
}
public void sendTestString(String s){
try {
outStream = btSocket.getOutputStream();
} catch (IOException e)
{
Log.e(TAG, "sendTestByte: OutputStream creation failed.", e);
}
try {
outStream.write(s.getBytes());
Log.d(TAG, "sendTestByte: OutputStream write succeeded.");
} catch (IOException e)
{
Log.e(TAG, "sendTestByte: OutputStream writefailed.", e);
}
}
public void onClick(View v){
switch(v.getId())
{
case R.id.toggleButton1:
this.sendTestString("1");
break;
case R.id.toggleButton2:
this.sendTestString("2");
break;
case R.id.toggleButton3:
this.sendTestString("3");
break;
}
}
#Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e5)
{
Log.e(TAG, "ON PAUSE: Couldn't flush output stream.", e5);
}
}
try {
btSocket.close();
} catch (IOException e6)
{
Log.e(TAG, "ON PAUSE: Unable to close socket.", e6);
}
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
My program crashes after pairing with the error message:
07-27 13:00:57.483: E/THINBTCLIENT(7855): sendTestByte: OutputStream writefailed.
07-27 13:00:57.483: E/THINBTCLIENT(7855): java.io.IOException: socket closed
07-27 13:00:57.483: E/THINBTCLIENT(7855): at
android.bluetooth.BluetoothSocket.write(BluetoothSocket.java:331)
...
What am I doing wrong?
Thanks.
If you are sure the connection is established without any error and you can get the socket, try assigning your OutputStream member in run() method as follows:
public void run()
{
mBluetoothAdapter.cancelDiscovery();
try
{
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e)
{
Log.e(TAG, "ON START: Socket creation failed.", e);
}
try
{
btSocket.connect();
} catch (IOException e)
{
Log.e(TAG, "sendTestByte: Socket connection failed.", e);
}
try
{
outStream = btSocket.getOutputStream();
} catch (IOException e)
{
Log.e(TAG, "sendTestByte: OutputStream creation failed.", e);
}
}
public void sendTestString(String s)
{
try
{
outStream.write(s.getBytes());
outSttream.flush(); // <-- Try flush to force sending data in buffer
Log.d(TAG, "sendTestByte: OutputStream write succeeded.");
} catch (IOException e)
{
Log.e(TAG, "sendTestByte: OutputStream writefailed.", e);
}
}
You are not actually closing socket but this should work. Make sure connection with master device is not lost before write() call

Categories

Resources