Code example for BluetoothSocket

Methods: close, connect, getInputStream, getOutputStream

0
        btAdapter.cancelDiscovery();
 
        // Establish the connection.  This will block until it connects. 
        Log.d(TAG, "Connecting...");
        try { 
            btSocket.connect();
            Log.d(TAG, "Connection ready");
        } catch (IOException e) {
            try { 
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure " + e2.getMessage());
            } 
        } 
 
        // Create a data stream so we can talk to server. 
        Log.d(TAG, "Creating Socket...");
 
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
    } 
 
    @Override 
    public void onPause() { 
        super.onPause(); 
 
        Log.d(TAG, "In onPause()...");
 
        try { 
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket. " + e2.getMessage());
        } 
    } 
 
    private void checkBTState() { 
        // Check for Bluetooth support and then check to make sure it is turned on 
        // Emulator doesn't support Bluetooth and will return null 
        if (btAdapter == null) {
            errorExit("Fatal Error", "Bluetooth not supported"); 
        } else { 
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "Bluetooth ON");
            } else { 
                //Prompt user to turn on Bluetooth 
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            } 
        } 
    } 
 
    private void errorExit(String title, String message) {
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
        finish();
    } 
 
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private BufferedReader br = null;
 
        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
 
 
            // Get the input and output streams, using temp objects because 
            // member streams are final 
            try { 
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
                br = new BufferedReader(new InputStreamReader(tmpIn));
            } catch (IOException ignored) {
            } 
 
            mmInStream = tmpIn;