连接蓝牙设备时出现问题

时间:2011-05-01 02:03:37

标签: android bluetooth

我正在尝试使用以下代码连接到设备...基本上是从BTchat源修改的。一切似乎都很顺利,但设备没有响应命令,我的手机仍然说配对但没有连接,设备说它没有连接。这让我很确定它确实没有连接,但没有发生错误。

我可以使用错误的UUID吗?

日志说:

04-30 18:51:10.116: DEBUG/BluetoothService(1228):     uuid(application): 00001101-0000-1000-8000-00805f9b34fb 1

04-30 18:51:10.116: DEBUG/BluetoothService(1228): Making callback for 00001101-0000-1000-8000-00805f9b34fb with result 1

04-30 18:51:10.131: VERBOSE/BluetoothEventRedirector(31561): Received android.bleutooth.device.action.UUID

我的代码正在打印到它连接的日志:

04-30 18:53:21.210: DEBUG/BTComm(1044): connect to: K4500-620963
04-30 18:53:21.225: INFO/BTComm(1044): BEGIN ConnectThread
04-30 18:53:26.272: DEBUG/BTComm(1044): connected to: K4500-620963
04-30 18:53:26.272: DEBUG/BTComm(1044): create ConnectedThread
04-30 18:53:26.280: DEBUG/BTComm(1044): setState() 0 -> 3
04-30 18:53:26.280: INFO/BTComm(1044): BEGIN ConnectedThread

这是我的整个代码: P

ublic class BTCom {
    // Debugging
    private static final String TAG = "BTComm";
    private static final boolean D = true;
    private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

 // Member fields
    private final BluetoothAdapter adapter;
    private final Handler handler;
    private ConnectThread connectThread;
    private ConnectedThread connectedThread;
    private int state;
    private Context context;
    private BluetoothDevice BTDevice;

 // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    public BTCom(Context context, Handler handler) {
        adapter = BluetoothAdapter.getDefaultAdapter();
        state = STATE_NONE;
        this.handler = handler;
        this.context = context;
    }




    private void checkBluetooth(){
        // check if device supports bluetooth
        if (adapter == null) {
            Toast.makeText(context, "ERROR: This device does not support Bluetooth communication"
                    , Toast.LENGTH_LONG).show();
            return;
        }
        // now make sure bluetooth is enabled
        if (!adapter.isEnabled()) {
            // if not, then prompt the user
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            context.startActivity(enableBtIntent);
        }
    }

    public BluetoothDevice getBTDevice(){
        Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
        BluetoothDevice foundDevice = null;
        BTDevice = null;
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // check if the name fits the pattern K4xxx-xxxxxx
                if (device.getName().matches("K4\\d\\d\\d-\\d\\d\\d\\d\\d\\d")){ 
                    foundDevice = device;
                    break;
                }
            }
            if (foundDevice == null){ // if we didn't find any
                Toast.makeText(context, 
                        "ERROR: No paired BTDevice device was found, please pair a BTDevice device to continue"
                        , Toast.LENGTH_LONG).show();
                return null;
            }
        }
        return foundDevice; // found a BTDevice!
    }


    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + this.state + " -> " + state);
        this.state = state;
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     */
    public synchronized void connect(BluetoothDevice device) {
        Log.d(TAG, "connect to: " + device.getName());

        // Cancel any thread attempting to make a connection
        if (connectThread != null) {connectThread.cancel(); connectThread = null;}


        // Cancel any thread currently running a connection
        if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}

        // Start the thread to connect with the given device
        connectThread = new ConnectThread(device);
        connectThread.start();
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        Log.d(TAG, "connected to: " + device.getName());

        // Cancel the thread that completed the connection
        if (connectThread != null) {connectThread.cancel(); connectThread = null;}

        // Cancel any thread currently running a connection
        if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}


        // Start the thread to manage the connection and perform transmissions
        connectedThread = new ConnectedThread(socket);
        connectedThread.start();
        setState(STATE_CONNECTED);

    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");

        if (connectThread != null) {
            connectThread.cancel();
            connectThread = null;
        }

        if (connectedThread != null) {
            connectedThread.cancel();
            connectedThread = null;
            setState(STATE_NONE);
        }
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (state != STATE_CONNECTED) return;
            r = connectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    private class ConnectThread extends Thread {
        private final BluetoothSocket socket;
        private final BluetoothDevice device;

        public ConnectThread(BluetoothDevice device) {
            this.device = device;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                tmp = device.createRfcommSocketToServiceRecord(uuid);
            } catch (IOException e) {
                Log.e(TAG, "Socket create failed", e);
            }
            socket = tmp;
        }

        public void run() {
            Log.i(TAG, "BEGIN ConnectThread");


            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                socket.connect();
            } catch (IOException e) {
                // Close the socket
                try {
                    socket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() socket during connection failure", e2);
                }
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (BTCom.this) {
                connectThread = null;
            }

            // Start the connected thread
            connected(socket, this.device);
        }

        public void cancel() {
            try {
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket socket;
        private final InputStream inStream;
        private final OutputStream outStream;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            this.socket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            inStream = tmpIn;
            outStream = tmpOut;
        }

        public void run() {
            Log.i(TAG, "BEGIN ConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = inStream.read(buffer);

                 // Send the obtained bytes to the UI Activity
                    handler.obtainMessage(KestrelTest.MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    // Start the service over to restart listening mode
                    break;
                }
            }
        }

        /**
         * Write to the connected OutStream.
         * @param buffer  The bytes to write
         */
        public void write(byte[] buffer) {
            try {
                outStream.write(buffer);
                Log.i(TAG, "Sending " + buffer.length + " bytes");
                Log.i(TAG, "Sending: " + new String(buffer));

            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

}

我很难过为什么不连接......有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您要连接的设备是什么?也许该设备需要主机(Android)系统支持某些配置文件,如A2DP,BIP,BPP等。

蓝牙聊天程序可创建基本的客户端 - 服务器连接,并且不需要支持蓝牙配置文件。

要在Android上实施蓝牙配置文件支持,有一个名为“Sybase-iAnywhere-Blue-SDK-for-Android”的项目,它取代了Android的版本,并提供了所有接口到底层蓝牙配置文件和协议。使用此功能,可以使用此SDK提供的BPP配置文件,使用您的Android手机通过蓝牙进行打印。

请参阅以下链接了解详情:链接1:http://www.sybase.com/detail?id=1064424链接2:http://www.sybase.com/products/allproductsa-z/mobiledevicesdks/bluetoothsdks

iAnywhere Blue SDK for Android支持的应用程序配置文件包括:

免提(HFP) 高级音频分配(A2DP) A / V遥控器(AVRCP) 文件传输协议(FTP) 对象推送协议(OPP) SIM卡访问(SAP) 电话簿访问(PBAP) 消息访问配置文件(MAP) 人机界面(HID) 基础印刷(BPP) 基本成像(BIP)