Android中与蓝牙设备的第二次连接失败

时间:2014-04-07 11:09:52

标签: java android bluetooth android-bluetooth

我正在尝试在Android 4.4中建立蓝牙连接,但BluetoothSocket的连接方法似乎工作奇怪。我的应用程序可以假设设备已经绑定,因此我可以通过MAC地址连接。问题是它在第一次绑定设备时完美且立即连接,但如果我重新启动它,则不会建立连接并发生超时。我在while循环中执行此操作直到它连接,但实际解决方案需要很长时间,或者根本不起作用。以下是我的代码示例:

public class BluetoothManager{

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothDevice bluetoothDevice;
    private BluetoothSocket socket;
    private OutputStream output;
    private InputStream input;

    public BluetoothManager() {
        /***************/
        /* Constructor */
        /***************/

        // lock = new Object();

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public boolean turnOnBluetooth() {
        /**************************************/
        /* Turn on Bluetooth an notify result */
        /**************************************/

        // check if bluetooth is supported
        if (bluetoothAdapter == null) {
            return (false);
        } else {
            // enable Bluetooth if not enabled yet
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
            }
            while (!bluetoothAdapter.isEnabled()) {
                Log.i("Debug", "Waiting for bluetooth to turn on");
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            return (true);
        }
    }

    public boolean turnOffBluetooth() {
        /***************************************/
        /* Turn off Bluetooth an notify result */
        /***************************************/

        // check if bluetooth is supported
        if (bluetoothAdapter == null) {
            return (false);
        } else {
            // disable Bluetooth if not enabled yet
            if (bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.disable();
            }
            while (bluetoothAdapter.isEnabled()) {
                Log.i("Debug
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            return (true);
        }
    }

    public boolean configureBluetooth(String MACaddress) {
        /***********************************************************************/
        /* Configures to the specified bluetooth device and returns the result */
        /***********************************************************************/

        Log.i("Debug", "Connecting to Bluetooth Device");
        bluetoothDevice = bluetoothAdapter.getRemoteDevice(MACaddress);

        return (true);
    }

    @SuppressLint("NewApi")
    public void createSocket() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        final UUID serialUUID = UUID
                .fromString("00001101-0000-1000-8000-00805F9B34FB");

        socket = null;
        output = null;
        input = null;


         Method m = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
         socket = (BluetoothSocket)m.invoke(bluetoothDevice, 1);
    }


    @SuppressLint("NewApi")
    public void connect() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        /************************************/
        /* Connects to the bluetooth device */
        /************************************/

        Log.i("Debug", "en connect");
        while (!socket.isConnected()) { // we try until the connection is established
            try {
                socket.connect();
                output = socket.getOutputStream();
                input = socket.getInputStream();
            } catch (IOException e) {
                Log.i("Depuración", "Connection not established. Another run : "+e);
                try {
                    Thread.sleep(1000);
                } catch (Exception e1) {
                }
            }
        }
    }

    public void terminateConnection() throws IOException {
        Log.i("Debug", "terminating connection");
        if(output!=null){
            Log.i("Debug", "output!=null - stop streaming");
            stopStreaming();
        }

        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
        if(input!=null){
            Log.i("Debug", "input!=null");
            input.close();
            input=null;
        }
        if(output!=null){
            Log.i("Depuración", "output!=null");
            output.close();
            output = null;
        }
        if(socket!=null){
            Log.i("Debug", "socket!=null");
            socket.close();
            socket=null;
        }
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
        turnOffBluetooth();
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
        System.gc();
    }

如果我从MainActivity调用此方法,它可以工作,但只有第一次绑定设备。如果我再次启动应用程序,我会尝试连接到设备:

socket.connect();

我怀疑它与我终止连接的方式有关,但我无法弄明白。这是方法的顺序调用:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bluetoothManager = new BluetoothManager();
        try {
            bluetoothManager.terminateConnection();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        bluetoothManager.turnOffBluetooth();
        bluetoothManager.turnOnBluetooth();

        boolean configured = false;
        while (!configured) {
            Log.i("Debug", "Configuration Attemp");
            configured = bluetoothManager.configureBluetooth(MACaddress);
        }

        Log.i("Debug", "Bluetooth Configured");

        try {
            bluetoothManager.createSocket();
        } catch (NoSuchMethodException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalArgumentException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InvocationTargetException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Log.i("Depuración", "Socket created");

        try {
            bluetoothManager.connect();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i("Debug", "Connected!!!!");

protected void onPause() {
    Log.i("Debug", "On pause");

    // TODO Auto-generated method stub
    try {
        bluetoothManager.terminateConnection();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    bluetoothManager = null;
    System.gc();
    super.onPause();
};

我一直在努力解决这个问题,我仍然找不到理由。

1 个答案:

答案 0 :(得分:0)

嗯,我不是专业人士,但看起来你应该在应用关闭时致电bluetoothManager.terminateConnection();,让我们说onDestroy,而不是onCreate;如果之前的连接没有正确终止,我也有连接问题。只需尝试将此方法添加到您的主要活动:

  @Override
  public void onDestroy(){
    if (bluetoothManager != null){
        bluetoothManager.terminateConnection();
    }
    super.onDestroy();
}
希望有所帮助。