Hi all,

I use a hardware bluetooth device and I need to connect it to my mobile
phone. I've follow the instruction on developer.android.com to set up a
bluetooth connection but I still have a problem. When I'm connecting to the
Bluetooth Socket with bluetoothSocket.connect() I don't catch any exception
so according to the docs, that mean I'm connected to my device. The problem
is I'm not... Here is my code :

    private class AcceptThread extends Thread {
        // The local server socket
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;

            // Create a new listening server socket
            try {
                tmp = mAdapter
                        .listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "listen() failed", e);
            }
            mmServerSocket = tmp;
        }

        public void run() {
            if (D)
                Log.d(TAG, "BEGIN mAcceptThread" + this);
            setName("AcceptThread");
            BluetoothSocket socket = null;

            // Listen to the server socket if we're not connected
            while (mState != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "accept() failed", e);
                    break;
                }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (BluetoothConnectionService.this) {
                        switch (mState) {
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            // Situation normal. Start the connected thread.
                            connected(socket, socket.getRemoteDevice());
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Either not ready or already connected.
Terminate
                            // new socket.
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted
socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            if (D)
                Log.i(TAG, "END mAcceptThread");
        }

        public void cancel() {
            if (D)
                Log.d(TAG, "cancel " + this);
            try {
                if (mmServerSocket != null)
                    mmServerSocket.close();
            } catch (Exception e) {
                Log.e(TAG, "close() of server failed", e);
            }
        }
    }

    /**
     * This thread runs while attempting to make an outgoing connection with
a
     * device. It runs straight through; the connection either succeeds or
     * fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;


        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket connection = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                // device.createRfcommSocketToServiceRecord(MY_UUID);
                Method m = device.getClass().getMethod("createRfcommSocket",
                        new Class[] { int.class });
                connection = (BluetoothSocket) m.invoke(device, 1);
                Utils.pause(100);
            } catch (Exception e) {
                Log.e(TAG, "create() failed", e);
            }
            mmSocket = connection;
        }

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

            if (mmSocket != null) {
                // Always cancel discovery because it will slow down a
                // connection
                    mAdapter.cancelDiscovery();

                // Make a connection to the BluetoothSocket
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    mmSocket.connect();
                } catch (Exception e1) {

                    Log.e(TAG, "connect failed", e1);
                    connectionFailed();

                    // Close the socket
                    try {
                        mmSocket.close();
                    } catch (IOException e2) {
                        Log.e(TAG,
                                "unable to close() socket during connection
failure",
                                e2);
                    }
                    // Start the service over to restart listening mode
                    BluetoothConnectionService.this.start();
                    return;
                }
                // Reset the ConnectThread because we're done
                synchronized (BluetoothConnectionService.this) {
                    mConnectThread = null;
                }

                // Start the connected thread
                connected(mmSocket, mmDevice);
            } else {
                connectionFailed();
                BluetoothConnectionService.this.start();
            }
        }

        public void cancel() {
            try {
                if (mmSocket != null) {
                    mmSocket.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 mmSocket;
        private final DataInputStream mmInStream;
        private final OutputStream mmOutStream;

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

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

            mmInStream = new DataInputStream(tmpIn);
            mmOutStream = tmpOut;
        }

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

            while (isConnected) {
                Utils.pause(5);
                isConnected = checkConnection();
            }
        }

        /**
         * Check if the connection is still alive
         *
         * @return true or false
         */
        private boolean checkConnection() {
            synchronized (mmInStream) {
                try {
                    int len = mmInStream.available();
                    if (len > 0) {// Checks the available amount
                        byte b[] = new byte[len];
                        mmInStream.readFully(b, 0, len);
                        mHandler.obtainMessage(MESSAGE_READ, len, -1, b)
                                .sendToTarget();
                    }
                    return true;
                } catch (IOException ioe) {
                    Log.e(TAG, "disconnected", ioe);
                    connectionLost();
                    return false; // Connection is lost.
                }
            }
        }


Thank you for your help !

  Best regards


SECU4 SA
Laurent Lugon Moulin

Technical & Development Assistant
 Technopôle 5
3960 Sierre – Switzerland

Office  :   +4127 4567 931
Fax      :   +4127 4567
935

Skype :   laurent.lugon.moulin

www.secu4.com

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to