android 开发之 Bluetooth

android  蓝牙串口连接代码


  BluetoothSocket tmp =null;

  // Get a BluetoothSocket for a  connection with the
  // given BluetootDevice

  try{
         tmp= device.createRfcommSocketToServiceRecord

(MY__UUID);


}catch(IOException e)
{
   log.e( TAG, "create() failed", e);

}


  然后是tmp 赋给 BluetoothSocket,接着调用connect 方法进行

蓝牙设备的连接。

   可是BluetoothSocket的connect的方法本身会报很多异常错误
   以下根据对蓝牙的一点研究可以通过一下方法解决:
   1.先进行蓝牙自动配对,配对成功,通过BluetoothSocket,然

后执行connect()方法。
    2. 通过 UUID 获得BluetoothSocket,然后先根据

mDevice.getBondState() 进行判断是否需要配对,最后执行

connect() 方法。

 
蓝牙连接线程

private class ConnectThread extends Thread
{
   String macAddrss="";
 public ConnectThread(String mac)
{
   macAddress=mac;

}
  public void run()
{
   connecting=true;
   connected=false;
if(  mBluetoothAdapter==null)
{
   mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();


}

    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
 mBluetoothAdapter.cancelDiscovery();


try{

    socket = mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);

}catch{IOException e}

Log.e(TAG, "Socket", e);

}
   while(!connected && connetTime<=10)
{
      connectDevice();
}

     public void cancel()

{
    try{
     socket.close();
      socket=null;


}catch(Exception e)
{
       e.printStackTrace();


}finally{
    connecting=false;

}

}



}

 
接下来是调用的是连接 设备的方法  connectDevice();


protected void connectDevice()
{

    try{
//  连接建立之前的先配对

    if(mBluetoothDevice.getBondState()== BluetoothDevice.BOND_NONE)
{
    Method  creMethod= BluetoothDevice.class.getMethod("createBond");


       creMethod.invoke(mBluetoothDevice);


}else{



}


}catch(Exception e) { 
            // TODO: handle exception 
            //DisplayMessage("无法配对!"); 
            e.printStackTrace(); 


}

   mBluetoothAdapter.cancelDiscovery();

     try{
     socket.connet();
 //DisplayMessage("连接成功!");
            //connetTime++;
            connected = true;
        } catch (IOException e) { 
            // TODO: handle exception 
            //DisplayMessage("连接失败!");
            connetTime++;
            connected = false;
            try { 
                socket.close();
                socket = null;
            } catch (IOException e2) { 
                // TODO: handle exception 
                Log.e(TAG, "Cannot close connection when connection failed"); 
            } 
        } finally {
            connecting = false;
        } 



}

 

方法3.利用反射通过端口获得BluetoothSocket,然后执行connect()方法。

 

    /**
     * <p>
     * 蓝牙连接线程
     * </p>
     * 
     * @author lsw
     * 
     */
    private class ConnectThread extends Thread {
        String macAddress = "";

        public ConnectThread(String mac) {
            macAddress = mac;
        }

        public void run() {
            connecting = true;
            connected = false;
            if(mBluetoothAdapter == null){
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            }
            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
            mBluetoothAdapter.cancelDiscovery();
            initSocket();                         
            //adapter.cancelDiscovery();
            while (!connected && connetTime <= 10) {
                try {
                    socket.connect();
                    connected = true;
                } catch (IOException e1) {
                    connetTime++;
                    connected = false;
                    // 关闭 socket
                    try {
                        socket.close();
                        socket = null;
                    } catch (IOException e2) {
                        //TODO: handle exception  
                        Log.e(TAG, "Socket", e2);
                    }
                } finally {
                    connecting = false;
                }
                //connectDevice();
            }
            // 重置ConnectThread 
            //synchronized (BluetoothService.this) {
               //ConnectThread = null;
            //}
        }

        public void cancel() {
            try {
                socket.close();
                socket = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connecting = false;
            }
        }
    }
复制代码

  接下来是初始化并得到BluetoothSocket的方法

  

复制代码
    /**
     * 取得BluetoothSocket
     */
    private void initSocket() {
        BluetoothSocket temp = null;
        try {            
            Method m = mBluetoothDevice.getClass().getMethod(
                    "createRfcommSocket", new Class[] { int.class });
            temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//这里端口为1            
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        socket = temp;
    }
复制代码

要点:1.蓝牙配对和连接是两回事,不可混为一谈。

   2.蓝牙串口连接可通过端口 (1-30)和UUID两种方法进行操作。

   3.通过UUID进行蓝牙连接最好先进行配对操作。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值