Android蓝牙:连接()/断开连接()

问题描述 投票:2回答:1

我目前正在设计一个应用程序,它需要连接到设备,写入/读取数据,并可靠地关闭连接。目前我有写/读固体。我断开连接然后重新连接是非常不可靠的,并且经常会使手机崩溃..有时候是Eclipse。我一直在寻找许多文章,试图弄明白......没有运气..

****连接功能**

public boolean connect()
{
  ConfigData.getInstance();
  BluetoothSocket tmp = null;
  BluetoothDevice device = ConfigData.m_SharedBluetoothDevice;
  Method m;
  try {

   tmp = device.createRfcommSocketToServiceRecord(MY_UUID);//(BluetoothSocket)
    m.invoke(device, 1);
  } catch (SecurityException e) { 
   e.printStackTrace();
  } catch (IllegalArgumentException e) {  
   e.printStackTrace();
  } 
  catch (IOException e) {
   e.printStackTrace();
  }
        ConfigData.m_SharedBluetoothSocket = tmp;
        try {
   ConfigData.m_SharedBluetoothSocket.connect();
   ConfigData.bIsBTConnected = true;
  } catch (IOException e) {
   try {
    closeSocket();
    m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
    tmp = (BluetoothSocket) m.invoke(device, 1);
   } catch (SecurityException e1) {
    e1.printStackTrace();
   } catch (NoSuchMethodException e1) {
    e1.printStackTrace();
   } catch (IllegalArgumentException e1) {
    e.printStackTrace();
   } catch (IllegalAccessException e1) {
    e.printStackTrace();
   } catch (InvocationTargetException e1) {
    e.printStackTrace();
   }
   ConfigData.m_SharedBluetoothSocket = tmp;
   try {
    ConfigData.m_SharedBluetoothSocket.connect();
    ConfigData.bIsBTConnected = true;
   } catch (IOException e1) {
    ConfigData.m_BluetoothException += e1.toString();
    ConfigData.bIsBTConnected = false;
    return false;

   }
   e.printStackTrace();
   return true;
  }
        return true;
 }

****断开功能**

 public void destroySocket()
 {
     try {
      if(m_InStream != null)
      {
       m_InStream.close();
       m_InStream = null;
      }
      if(m_OutStream != null)
      {
       m_OutStream.close();
       m_OutStream  = null;
      }
      if(ConfigData.m_SharedBluetoothSocket != null)
      {
       ConfigData.m_SharedBluetoothSocket.close();
       ConfigData.m_SharedBluetoothSocket = null;
      }
      if(m_InStream == null && m_OutStream == null && ConfigData.m_SharedBluetoothSocket == null)
   {
       ConfigData.bIsBTConnected = false;
   }
  } catch (IOException e1) {
   m_InStream = null;
   m_OutStream  = null;
   ConfigData.m_SharedBluetoothSocket = null;
   e1.printStackTrace();
  }
 }

因此断开连接成功并返回所有null。问题是,当我在第二次连接尝试时重新连接它时,它将只是坐在那里或完全崩溃手机,导致几次重启。

有没有人在这里有任何建议?它非常令人沮丧。任何帮助将非常感激!!

谢谢你,他们!权益

android bluetooth connect
1个回答
0
投票

你用的是哪款手机?什么OS?看到这个答案:Disconnect a bluetooth socket in Android

关闭实际上在某些HTC 2.1update1手机上无法正常工作

© www.soinside.com 2019 - 2024. All rights reserved.