Code example for BluetoothDevice

Methods: createRfcommSocketToServiceRecord, getName

0
    /** 
     * Start the ConnectThread to initiate a connection to a remote device. 
     * @param device  The BluetoothDevice to connect 
     */ 
    public synchronized void connect(BluetoothDevice device) {
    	RhoBluetoothManager.logi(TAG, "connect() to: " + device.getName());
 
        // Cancel any thread attempting to make a connection 
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        } 
 
        // Cancel any thread currently running a connection 
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
 
        // Start the thread to connect with the given device 
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    } 
 
    /** 
     * 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) {
    	RhoBluetoothManager.logi(TAG, "connected()");
 
        // Cancel the thread that completed the connection 
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
 
        // Cancel any thread currently running a connection 
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
 
        // Cancel the accept thread because we only want to connect to one device 
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
 
        // Start the thread to manage the connection and perform transmissions 
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();
 
        // Send the name of the connected device back to the UI Activity 
        //Message msg = mHandler.obtainMessage(RhoBluetoothManager.MESSAGE_DEVICE_NAME); 
        //Bundle bundle = new Bundle(); 
        //bundle.putString(RhoBluetoothManager.sharedInstance().DEVICE_NAME, device.getName()); 
        //msg.setData(bundle); 
        //mHandler.sendMessage(msg); 
    	RhoBluetoothManager.sharedInstance().onSessionConnectedDeviceName(device.getName());
 
 
        setState(STATE_CONNECTED);
    } 
 
    /** 
     * Stop all threads 
     */ 
    public synchronized void stop() { 
    	RhoBluetoothManager.logi(TAG, "stop()");
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = 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) {
    	RhoBluetoothManager.logi(TAG, "write()");
        // Create temporary object 
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread 
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        } 
        // Perform the write unsynchronized 
        r.write(out);
    } 
 
    /** 
     * Indicate that the connection attempt failed and notify the UI Activity. 
     */ 
    private void connectionFailed() { 
    	RhoBluetoothManager.logi(TAG, "connectionFailed()");
        setState(STATE_NONE);
 
        // Send a failure message back to the Activity 
        //Message msg = mHandler.obtainMessage(RhoBluetoothManager.MESSAGE_TOAST); 
        //Bundle bundle = new Bundle(); 
        //bundle.putString(RhoBluetoothManager.TOAST, "Unable to connect device"); 
        //msg.setData(bundle); 
        //mHandler.sendMessage(msg); 
        RhoBluetoothManager.sharedInstance().onSessionToast("Unable to connect device"); 
    } 
 
    /** 
     * Indicate that the connection was lost and notify the UI Activity. 
     */ 
    public void connectionLost() { 
    	RhoBluetoothManager.logi(TAG, "connectionLost()");
        setState(STATE_NONE);
 
        // Send a failure message back to the Activity 
        //Message msg = mHandler.obtainMessage(RhoBluetoothManager.MESSAGE_TOAST); 
        //Bundle bundle = new Bundle(); 
        //bundle.putString(RhoBluetoothManager.TOAST, "Device connection was lost"); 
        //msg.setData(bundle); 
        //mHandler.sendMessage(msg); 
        RhoBluetoothManager.sharedInstance().onSessionToast("Device connection was lost"); 
    } 
 
    /** 
     * This thread runs while listening for incoming connections. It behaves 
     * like a server-side client. It runs until a connection is accepted 
     * (or until cancelled). 
     */ 
    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() { 
        	RhoBluetoothManager.logi(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 (RhoBluetoothSession.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; 
                        } 
                    } 
                } 
            } 
            RhoBluetoothManager.logi(TAG, "END mAcceptThread");
        } 
 
        public void cancel() { 
        	RhoBluetoothManager.logi(TAG, "CANCEL mAcceptThread");
            try { 
                mmServerSocket.close();
            } catch (IOException 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 tmp = null;
 
            // Get a BluetoothSocket for a connection with the 
            // given BluetoothDevice 
            try { 
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "create() failed", e);
            } 
            mmSocket = tmp;
        }