Android蓝牙套接字IOException:“读取失败,套接字可能已关闭或超时" [英] Android Bluetooh Socket IOException: 'read failed, socket might be closed or timeout'

查看:157
本文介绍了Android蓝牙套接字IOException:“读取失败,套接字可能已关闭或超时"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过蓝牙与手机连接的蓝牙遥控器(我认为是通过自拍杆).它可以工作,可以拍照,但我想从应用程序中的遥控器接收信号以遥控音乐.

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.

问题:创建套接字后,如果没有IOException,我将无法连接到它.

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

这是所有代码:

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

错误在第131行,ConnectThread run()

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;
            }

错误显示:

以前有没有人遇到此错误,可以指出正确的方向?

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

推荐答案

这不是错误,是警告.警告发生后,您是否正在失去某种功能?如果不是这样,听起来好像您无法控制它,但根据此答案中的一些人的说法,也不必担心它:

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

这篇关于Android蓝牙套接字IOException:“读取失败,套接字可能已关闭或超时"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆