2014-04-07 67 views
3

我想在Android 4.4中建立蓝牙连接,但BluetoothSocket的连接方法似乎工作奇怪。我的应用可以假定设备已经绑定,所以我可以通过MAC地址连接。问题是它在第一次绑定设备时会立即完美连接,但如果我重新启动它,则连接不会建立并发生超时。我在一个while循环内做这件事,直到它连接起来,但是真正的解决方案需要很长的时间,或者根本不起作用。这里是我的代码示例:第二次连接到蓝牙设备失败Android

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

我一直在试图解决这个问题,我仍然无法找到一个理由。

+0

您是否提到了BluetoothChat示例应用程序?如果不是,请通过它。 –

+0

而不是等待500毫秒尝试侦听操作BluetoothAdapter.ACTION_STATE_CHANGED。 –

回答

0

嗯,我不是这个专业,但它看起来像你应该叫bluetoothManager.terminateConnection();当应用程序被关闭,可以说onDestroy,但不onCreate;如果以前的连接没有正确终止,我也有问题要连接。只是尝试添加此方法到您的主要活动:

@Override 
    public void onDestroy(){ 
    if (bluetoothManager != null){ 
     bluetoothManager.terminateConnection(); 
    } 
    super.onDestroy(); 
} 

希望有帮助。

+0

你的BluetoothManager究竟是什么?你可以给一个文档参考或至少一个父包名称? – milosmns