Android Bluetooh Socket IOException: 'read fai

2019-08-12 15:11发布

问题:

I have a Bluetooth remote control (I think from a selfie stick) connected with my phone via bluetooth. It works, it can take pictures but I want to receive signals from the remote control in my application to remotely control music.

The Problem: after I created the socket I cant connect to it without IOException.

Here is all the code:

public class MainActivity extends Activity {

BluetoothAdapter btAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
String tag = "debugging";
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        Log.i(tag, "in handler");
        super.handleMessage(msg);
        switch(msg.what){
        case SUCCESS_CONNECT:
            // DO something
            ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
            Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
            String s = "successfully connected";
            connectedThread.write(s.getBytes());
            Log.i(tag, "connected");
            break;
        case MESSAGE_READ:
            byte[] readBuf = (byte[])msg.obj;
            String string = new String(readBuf);
            Toast.makeText(getApplicationContext(), string, 0).show();
            break;
        }
    }
};
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try{
     btAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice device = getDeviceByName("AB Shutter 3");

    ConnectThread connect = new ConnectThread(device);
    connect.start();


      } catch (Exception e) {
        e.printStackTrace();

    }

}

private BluetoothDevice getDeviceByName(String printerName) 
{
    Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();

    BluetoothDevice remoteDevice;

    for (BluetoothDevice device : pairedDevices) 
    {
        if (device.getName() == null)
            continue;
        if (device.getName().contains(printerName)) 
        {
            Log.e("","device name: "+device.getName());
            remoteDevice = device;
            return remoteDevice;
        }
    }
    return null;
}
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
            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");
                e.printStackTrace();

            }
            mmSocket = tmp;
        }

        public void run() {
            try {   
            // Cancel discovery because it will slow down the connection
            btAdapter.cancelDiscovery();
            Log.i(tag, "connect - run");

                mmSocket.connect();
                Log.i(tag, "connect - succeeded");
            } catch (Exception connectException) {  
                Log.i(tag, "connect failed");
                // Unable to connect; close the socket and get out
                 connectException.printStackTrace();
                return;
            }

            // Do work to manage the connection (in a separate thread)

            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
        }

    }

    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) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer;  // 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
                    buffer = new byte[1024];
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();

                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }
            }
        }

        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }
    }
}

The Error is in line 131, ConnectThread run()

    try {   
            // Cancel discovery because it will slow down the connection
            btAdapter.cancelDiscovery();
            Log.i(tag, "connect - run");

                mmSocket.connect();                       //Here it fails
                Log.i(tag, "connect - succeeded");
            } catch (Exception connectException) {  
                Log.i(tag, "connect failed");
                // Unable to connect; close the socket and get out
                 connectException.printStackTrace();
                return;
            }

The Error shows:

Has anyone encountered this error before and can point me in the right direction?

回答1:

That's not an error, it's a warning. Are you losing some kind of functionality after the warning occurs? If not, it doesn't sound like you have control over it, but also don't need to worry about it according to several people in this answer: https://stackoverflow.com/a/24229604/3299157