在断开Android的蓝牙接口 [英] Disconnect a bluetooth socket in Android

查看:191
本文介绍了在断开Android的蓝牙接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的一个程序,从Android手机,我要作为客户端连接到蓝牙医疗传感器。我使用的是官方的蓝牙API,并在连接(SPP配置文件)没有问题,但是当我结束插槽,传感器仍然连接到我的手机(虽然我关闭连接)。

有没有办法让一个蓝牙断线?我觉得有一个名为ACTION_ACL_CONNECTED意图,它做到这一点。谁能解释我如何使用它?

在此先感谢。

编辑:这里是code,如果有人需要更多的信息,这是一个Nonin 4100医用传感器

 设置< BluetoothDevice类> pairedDevices = Activa.myBluetoothAdapter.getBondedDevices();
        //如果有配对设备
        如果(pairedDevices.size()大于0){
            //循环配对设备
            对于(BluetoothDevice类设备:pairedDevices){
                //添加姓名和地址到一个数组适配器在ListView显示
                字符串名称= device.getName();
                如果(name.contains(Nonin)){
                    尝试 {
                        发现= TRUE;
//插座= device.createRfcommSocketToServiceRecord(UUID.fromString(00001101-0000-1000-8000-00805F9B34FB));
// handler.sendEmptyMessage(5);
// Activa.myBluetoothAdapter.cancelDiscovery();
// Socket.connect()的;
                        BluetoothDevice类HXM = BluetoothAdapter.getDefaultAdapter()getRemoteDevice(device.getAddress())。
                        法米;
                        尝试 {
                            M = hxm.getClass()实现getMethod(createRfcommSocket,新的等级[] {} int.class)。
                            插座=(的BluetoothSocket)m.invoke(HXM,Integer.valueOf(1));
                            handler.sendEmptyMessage(5);
                            Socket.connect()的;
                        }赶上(例外五){
                            handler.sendEmptyMessage(7);
                            e.printStackTrace();
                            打破;
                        }
                        handler.sendEmptyMessage(6);
                        在的InputStream = socket.getInputStream();
                        的OutputStream出= socket.getOutputStream();
                        byte []的检索= {0x44,0X31};
                        out.write(检索);
                        byte []的ACK =新的字节[1];
                        in.read(ACK);
                        如果(ACK [0] == 0x15){
                            cancelMeasurement();
                            返回;
                        }
                        byte []的数据=新的字节[3];
                        长timeStart = System.currentTimeMillis的();
                        this.timePassed = System.currentTimeMillis的() -  timeStart;
                        而((this.timePassed≤(this.time))及及(this.finished)){
                            尝试 {
                                in.read(数据);
                                过程数据(数据);
                                视频下载(1000);
                                this.timePassed = System.currentTimeMillis的() -  timeStart;
                            }赶上(例外五){
                                e.printStackTrace();
                            }
                        }
                        附寄();
                        out.close();
                        socket.close();
                    }赶上(IOException异常E){
                        e.printStackTrace();
                    }
                }
            }
        }
}
 

解决方案

请记住先关闭输入/输出流,然后关闭套接字。

通过关闭流,您揭开序幕,断开连接的过程。当您关闭套接字,连接应充分分解。

如果您在流之前关闭套接字,你可能会绕过某些关机步骤,如(正确)收盘物理层连接。

下面是我使用的方法时,它的时间崩溃的连接。

  / **
 *复位输入和输出流,并确保关闭套接字。
 *此方法将被关闭()过程中使用,以确保在连接一个关闭过程中正确关闭。
 * @返回
 * /
私人无效resetConnection(){
        如果(mBTInputStream!= NULL){
                尝试{mBTInputStream.close();}赶上(例外五){}
                mBTInputStream = NULL;
        }

        如果(mBTOutputStream!= NULL){
                尝试{mBTOutputStream.close();}赶上(例外五){}
                mBTOutputStream = NULL;
        }

        如果(mBTSocket!= NULL){
                尝试{mBTSocket.close();}赶上(例外五){}
                mBTSocket = NULL;
        }

}
 

编辑:添加code的连接():

  //蓝牙适配器,它提供了访问蓝牙功能。
BluetoothAdapter mBTAdapter = NULL;
//插座重新presents的开放连接。
的BluetoothSocket mBTSocket = NULL;
//设备重新presents同行
BluetoothDevice类mBTDevice = NULL;

//流
InputStream的mBTInputStream = NULL;
OutputStream的mBTOutputStream = NULL;

static final的UUID UUID_RFCOMM_GENERIC = UUID.fromString(00001101-0000-1000-8000-00805F9B34FB);

/ **
 *尝试建立与对端的连接。
 *这个方法同步运行,并为一个或多个秒块,同时完成其事
 *这样称呼它从一个非UI线程!
 * @返回 - 如果已经建立连接返回true,就可以使用了。否则为false。
 * /
私人布尔连接(){

        //重置所有流和插座。
        resetConnection();

        //确保对被定义为基于MAC有效的设备。如果没有那么做。
        如果(mBTDevice == NULL)
                mBTDevice = mBTAdapter.getRemoteDevice(mPeerMAC);

        //做一个RFCOMM结合。
        尝试{mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
        }赶上(例外E1){
                MSG(连接():无法通过UUID结合RFCOMM味精=+ e1.getMessage());
                返回false;
        }

        MSG(连接():尝试连接。);

        尝试 {
                mBTSocket.connect();
        }赶上(例外五){
                MSG(连接():在连接过程中引发的异常:+ e.getMessage());
                返回false;
        }

        MSG(连接():连接!);

        尝试 {
                mBTOutputStream = mBTSocket.getOutputStream();
                mBTInputStream = mBTSocket.getInputStream();
        }赶上(例外五){
                MSG(连接():错误连接I / O流套接字味精=+ e.getMessage());
                返回false;
        }

        返回true;
}
 

I'm developing a program in which, from an Android Phone, I have to connect as a client to a Bluetooth medical sensor. I'm using the official Bluetooth API and no problem during connection (SPP profile), but when I end the socket, the sensor is still connected to my phone (although I have close the connection).

Are there any way to make a Bluetooth disconnection? I think there is an intent called ACTION_ACL_CONNECTED, which does that. Can anyone explain me how to use this?

Thanks in advance.

EDITED: Here is the code, if anyone needs additional info, it's a Nonin 4100 medical sensor.

Set<BluetoothDevice> pairedDevices = Activa.myBluetoothAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                String name = device.getName();
                if (name.contains("Nonin")) {
                    try {
                        found = true;
//                      socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//                      handler.sendEmptyMessage(5);
//                      Activa.myBluetoothAdapter.cancelDiscovery();
//                      socket.connect();
                        BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress());
                        Method m;
                        try {
                            m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
                            socket = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1));
                            handler.sendEmptyMessage(5);
                            socket.connect();
                        } catch (Exception e) {
                            handler.sendEmptyMessage(7);
                            e.printStackTrace();
                            break;
                        }
                        handler.sendEmptyMessage(6);
                        InputStream in = socket.getInputStream();
                        OutputStream out = socket.getOutputStream();
                        byte[] retrieve = { 0x44, 0x31};
                        out.write(retrieve);
                        byte [] ack = new byte [1];
                        in.read(ack);
                        if (ack[0] == 0x15) {
                            cancelMeasurement();
                            return;
                        }
                        byte [] data = new byte [3];
                        long timeStart = System.currentTimeMillis();
                        this.timePassed = System.currentTimeMillis() - timeStart;
                        while ((this.timePassed < (this.time))&&(this.finished)) {
                            try {
                                in.read(data);
                                processData(data);
                                Thread.sleep(1000);
                                this.timePassed = System.currentTimeMillis() - timeStart;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        in.close();
                        out.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
}

解决方案

Please remember to close your Input/output streams first, then close the socket.

By closing the streams, you kick off the disconnect process. After you close the socket, the connection should be fully broken down.

If you close the socket before the streams, you may be bypassing certain shutdown steps, such as the (proper) closing of the physical layer connection.

Here's the method I use when its time to breakdown the connection.

/**
 * Reset input and output streams and make sure socket is closed. 
 * This method will be used during shutdown() to ensure that the connection is properly closed during a shutdown.  
 * @return
 */
private void resetConnection() {
        if (mBTInputStream != null) {
                try {mBTInputStream.close();} catch (Exception e) {}
                mBTInputStream = null;
        }

        if (mBTOutputStream != null) {
                try {mBTOutputStream.close();} catch (Exception e) {}
                mBTOutputStream = null;
        }

        if (mBTSocket != null) {
                try {mBTSocket.close();} catch (Exception e) {}
                mBTSocket = null;
        }

}

EDIT: Adding code for connect():

// bluetooth adapter which provides access to bluetooth functionality. 
BluetoothAdapter        mBTAdapter      = null;
// socket represents the open connection.
BluetoothSocket         mBTSocket   = null;
// device represents the peer
BluetoothDevice         mBTDevice       = null; 

// streams
InputStream           mBTInputStream  = null;
OutputStream          mBTOutputStream = null;

static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

/**
 * Try to establish a connection with the peer. 
 * This method runs synchronously and blocks for one or more seconds while it does its thing 
 * SO CALL IT FROM A NON-UI THREAD!
 * @return - returns true if the connection has been established and is ready for use. False otherwise. 
 */
private  boolean connect() {

        // Reset all streams and socket.
        resetConnection();

        // make sure peer is defined as a valid device based on their MAC. If not then do it. 
        if (mBTDevice == null) 
                mBTDevice = mBTAdapter.getRemoteDevice(mPeerMAC);

        // Make an RFCOMM binding. 
        try {mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
        } catch (Exception e1) {
                msg ("connect(): Failed to bind to RFCOMM by UUID. msg=" + e1.getMessage());
                return false;
        }

        msg ("connect(): Trying to connect.");

        try {
                mBTSocket.connect();
        } catch (Exception e) {
                msg ("connect(): Exception thrown during connect: " + e.getMessage());
                return false;
        }

        msg ("connect(): CONNECTED!");

        try {
                mBTOutputStream = mBTSocket.getOutputStream();
                mBTInputStream  = mBTSocket.getInputStream();
        } catch (Exception e) {
                msg ("connect(): Error attaching i/o streams to socket. msg=" + e.getMessage());
                return false;
        }

        return true;
}

这篇关于在断开Android的蓝牙接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆