baidu_35257469
baidu_35257469
采纳率0%
2016-06-08 09:51 阅读 3.3k

android蓝牙Socket.connect失败,socket might be closed

代码如下,测试发现toast直到“mmsocket成功”都是有的,mmSocket.connect(); 那失败了,抛出“连接服务端异常2”
protected void onResume() {

         if(BluetoothMsg.isOpen)  
            {  
                Toast.makeText(mContext, "连接已经打开,可以通信。如果要再建立连接,请先断开!", Toast.LENGTH_SHORT).show();  
                return;  
            }  

// 如果点选了远程设备去连接,则本机是客户端, 开启客户端线程,接收输入流数据
if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.CLIENT)

{

String address = BluetoothMsg.BlueToothAddress; //将在UI界面选中连接的蓝牙地址赋给address
if(!address.equals("null")) //如果蓝牙地址不为空
{

//在mainactivity中的get到的本地蓝牙适配器实例化成了blueadapter,在这个activity中在开头实例化成了 mBluetoothAdapter,但是它们是同一个

                    device = mBluetoothAdapter.getRemoteDevice(address);//根据蓝牙地址获取远程蓝牙设备    

// mBluetoothAdapter.cancelDiscovery();
if (device != null) {
Toast.makeText(mContext, "device成功 !", Toast.LENGTH_SHORT).show();
}
clientConnectThread = new clientThread(device); //新建并启动一个客户端线程
clientConnectThread.start();

BluetoothMsg.isOpen = true; //将BluetoothMsg类里的isOpen常量改为true
}

else

{

Toast.makeText(mContext, "蓝牙地址为空 !", Toast.LENGTH_SHORT).show();

}

}

// 如果本机是服务器,开启服务端线程,也接收输入流数据
else if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.SERVICE)

{

            }  
        super.onResume();  
    }  



        //2开启客户端  读取数据            
        private class  clientThread extends Thread 
        {  
            private final BluetoothSocket mmSocket;  

            public clientThread(BluetoothDevice device) 
            {  

                BluetoothSocket tmp = null;  

                try 
                {  
                    tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
                } catch (IOException e) {  
                    Log.e("connect", "", e);  
                    Message msg = new Message();  
                    msg.obj = "连接服务端异常1!断开连接重新试一试。";  
                    msg.what = 0;  
                    LinkDetectedHandler.sendMessage(msg);  
                }  
                mmSocket = tmp; 
                if (mmSocket!= null){
                    Toast.makeText(mContext, "mmSocket成功", Toast.LENGTH_SHORT).show();
                }
            }  

            public void run() { 
                mBluetoothAdapter.cancelDiscovery();

                try {  

                    mmSocket.connect(); 



                } catch (IOException e) {  

                    Log.e("connect", "", e);  
                    Message msg = new Message();  
                    msg.obj = "连接服务端异常2!断开连接重新试一试。";  
                    msg.what = 0;  
                    LinkDetectedHandler.sendMessage(msg);
                    return;  
                }  

            }  


        }  
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

相关推荐