Problems with BluetoothChat Sample Applicaiton


  1. MrAlt

    MrAlt Member

    Hello All,

    I have been working on an Application to communicate with an ELM327 dongle via bluetooth. This will be used to communicate with an Engine Control Unit via the OBDII port. I have the app almost entirely developed in terms of what to do with the data that I gather and how to present it graphically.

    I am currently trying to work out the bluetooth connection code, and I an using the BluetoothChat sample as a reference. I have browsed the forums and found a few mistakes already, I have already changed my UUID in order to connect but I am running into other problems...

    I can connect fine, and even read the start up commands from the dongle as they are sent to the chat application

    HOWEVER - When I try to send a command the application shows something like this...

    CAN OBDII: ELM327 v1.2a> (This is good, this means the connection was established and the dongle is ready to communicate)
    Me:>ATRV (should return a voltage level)
    CAN OBDII:>ATRV

    - This is the problem I have, it mimics exactly what I send almost insantly, and if I wait a few second i will see the following

    CAN OBDII:>

    Which is a prompt to recieve a command, so I am guessing that there is an error somewhere in the code to write the data to the output stream?

    Any Suggestions?
    Code (Text):
    1. package com.example.android.BluetoothChat;
    2.  
    3. import android.app.Activity;
    4. import android.bluetooth.BluetoothAdapter;
    5. import android.bluetooth.BluetoothDevice;
    6. import android.content.Intent;
    7. import android.os.Bundle;
    8. import android.os.Handler;
    9. import android.os.Message;
    10. import android.util.Log;
    11. import android.view.KeyEvent;
    12. import android.view.Menu;
    13. import android.view.MenuInflater;
    14. import android.view.MenuItem;
    15. import android.view.View;
    16. import android.view.Window;
    17. import android.view.View.OnClickListener;
    18. import android.view.inputmethod.EditorInfo;
    19. import android.widget.ArrayAdapter;
    20. import android.widget.Button;
    21. import android.widget.EditText;
    22. import android.widget.ListView;
    23. import android.widget.TextView;
    24. import android.widget.Toast;
    25.  
    26. /**
    27.  * This is the main Activity that displays the current chat session.
    28.  */
    29. public class BluetoothChat extends Activity {
    30.     // Debugging
    31.     private static final String TAG = "BluetoothChat";
    32.     private static final boolean D = true;
    33.  
    34.     // Message types sent from the BluetoothChatService Handler
    35.     public static final int MESSAGE_STATE_CHANGE = 1;
    36.     public static final int MESSAGE_READ = 2;
    37.     public static final int MESSAGE_WRITE = 3;
    38.     public static final int MESSAGE_DEVICE_NAME = 4;
    39.     public static final int MESSAGE_TOAST = 5;
    40.  
    41.     // Key names received from the BluetoothChatService Handler
    42.     public static final String DEVICE_NAME = "device_name";
    43.     public static final String TOAST = "toast";
    44.  
    45.     // Intent request codes
    46.     private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    47.     private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    48.     private static final int REQUEST_ENABLE_BT = 3;
    49.  
    50.     // Layout Views
    51.     private TextView mTitle;
    52.     private ListView mConversationView;
    53.     private EditText mOutEditText;
    54.     private Button mSendButton;
    55.  
    56.     // Name of the connected device
    57.     private String mConnectedDeviceName = null;
    58.     // Array adapter for the conversation thread
    59.     private ArrayAdapter<String> mConversationArrayAdapter;
    60.     // String buffer for outgoing messages
    61.     private StringBuffer mOutStringBuffer;
    62.     // Local Bluetooth adapter
    63.     private BluetoothAdapter mBluetoothAdapter = null;
    64.     // Member object for the chat services
    65.     private BluetoothChatService mChatService = null;
    66.  
    67.  
    68.     @Override
    69.     public void onCreate(Bundle savedInstanceState) {
    70.         super.onCreate(savedInstanceState);
    71.         if(D) Log.e(TAG, "+++ ON CREATE +++");
    72.  
    73.         // Set up the window layout
    74.         requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    75.         setContentView(R.layout.main);
    76.         getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
    77.  
    78.         // Set up the custom title
    79.         mTitle = (TextView) findViewById(R.id.title_left_text);
    80.         mTitle.setText(R.string.app_name);
    81.         mTitle = (TextView) findViewById(R.id.title_right_text);
    82.  
    83.         // Get local Bluetooth adapter
    84.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    85.  
    86.         // If the adapter is null, then Bluetooth is not supported
    87.         if (mBluetoothAdapter == null) {
    88.             Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
    89.             finish();
    90.             return;
    91.         }
    92.     }
    93.  
    94.     @Override
    95.     public void onStart() {
    96.         super.onStart();
    97.         if(D) Log.e(TAG, "++ ON START ++");
    98.  
    99.         // If BT is not on, request that it be enabled.
    100.         // setupChat() will then be called during onActivityResult
    101.         if (!mBluetoothAdapter.isEnabled()) {
    102.             Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    103.             startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    104.         // Otherwise, setup the chat session
    105.         } else {
    106.             if (mChatService == null) setupChat();
    107.         }
    108.     }
    109.  
    110.     @Override
    111.     public synchronized void onResume() {
    112.         super.onResume();
    113.         if(D) Log.e(TAG, "+ ON RESUME +");
    114.  
    115.         // Performing this check in onResume() covers the case in which BT was
    116.         // not enabled during onStart(), so we were paused to enable it...
    117.         // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
    118.         if (mChatService != null) {
    119.             // Only if the state is STATE_NONE, do we know that we haven't started already
    120.             if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
    121.               // Start the Bluetooth chat services
    122.               mChatService.start();
    123.             }
    124.         }
    125.     }
    126.  
    127.     private void setupChat() {
    128.         Log.d(TAG, "setupChat()");
    129.  
    130.         // Initialize the array adapter for the conversation thread
    131.         mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
    132.         mConversationView = (ListView) findViewById(R.id.in);
    133.         mConversationView.setAdapter(mConversationArrayAdapter);
    134.  
    135.         // Initialize the compose field with a listener for the return key
    136.         mOutEditText = (EditText) findViewById(R.id.edit_text_out);
    137.         mOutEditText.setOnEditorActionListener(mWriteListener);
    138.  
    139.         // Initialize the send button with a listener that for click events
    140.         mSendButton = (Button) findViewById(R.id.button_send);
    141.         mSendButton.setOnClickListener(new OnClickListener() {
    142.             public void onClick(View v) {
    143.                 // Send a message using content of the edit text widget
    144.                 TextView view = (TextView) findViewById(R.id.edit_text_out);
    145.                 String message = view.getText().toString();
    146.                 sendMessage(message);
    147.             }
    148.         });
    149.  
    150.         // Initialize the BluetoothChatService to perform bluetooth connections
    151.         mChatService = new BluetoothChatService(this, mHandler);
    152.  
    153.         // Initialize the buffer for outgoing messages
    154.         mOutStringBuffer = new StringBuffer("");
    155.     }
    156.  
    157.     @Override
    158.     public synchronized void onPause() {
    159.         super.onPause();
    160.         if(D) Log.e(TAG, "- ON PAUSE -");
    161.     }
    162.  
    163.     @Override
    164.     public void onStop() {
    165.         super.onStop();
    166.         if(D) Log.e(TAG, "-- ON STOP --");
    167.     }
    168.  
    169.     @Override
    170.     public void onDestroy() {
    171.         super.onDestroy();
    172.         // Stop the Bluetooth chat services
    173.         if (mChatService != null) mChatService.stop();
    174.         if(D) Log.e(TAG, "--- ON DESTROY ---");
    175.     }
    176.  
    177.     private void ensureDiscoverable() {
    178.         if(D) Log.d(TAG, "ensure discoverable");
    179.         if (mBluetoothAdapter.getScanMode() !=
    180.             BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
    181.             Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    182.             discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    183.             startActivity(discoverableIntent);
    184.         }
    185.     }
    186.  
    187.     /**
    188.      * Sends a message.
    189.      * @param message  A string of text to send.
    190.      */
    191.     private void sendMessage(String message) {
    192.         // Check that we're actually connected before trying anything
    193.         if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
    194.             Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
    195.             return;
    196.         }
    197.  
    198.         // Check that there's actually something to send
    199.         if (message.length() > 0) {
    200.             // Get the message bytes and tell the BluetoothChatService to write
    201.             byte[] send = message.getBytes();
    202.             mChatService.write(send);
    203.  
    204.             // Reset out string buffer to zero and clear the edit text field
    205.            mOutStringBuffer.setLength(0);
    206.            mOutEditText.setText(mOutStringBuffer);
    207.         }
    208.     }
    209.  
    210.     // The action listener for the EditText widget, to listen for the return key
    211.     private TextView.OnEditorActionListener mWriteListener =
    212.         new TextView.OnEditorActionListener() {
    213.         public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    214.             // If the action is a key-up event on the return key, send the message
    215.             if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
    216.                 String message = view.getText().toString();
    217.                 sendMessage(message);
    218.             }
    219.             if(D) Log.i(TAG, "END onEditorAction");
    220.             return true;
    221.         }
    222.     };
    223.  
    224.     // The Handler that gets information back from the BluetoothChatService
    225.     private final Handler mHandler = new Handler() {
    226.         @Override
    227.         public void handleMessage(Message msg) {
    228.             switch (msg.what) {
    229.             case MESSAGE_STATE_CHANGE:
    230.                 if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
    231.                 switch (msg.arg1) {
    232.                 case BluetoothChatService.STATE_CONNECTED:
    233.                     mTitle.setText(R.string.title_connected_to);
    234.                     mTitle.append(mConnectedDeviceName);
    235.                     mConversationArrayAdapter.clear();
    236.                     break;
    237.                 case BluetoothChatService.STATE_CONNECTING:
    238.                     mTitle.setText(R.string.title_connecting);
    239.                     break;
    240.                 case BluetoothChatService.STATE_LISTEN:
    241.                 case BluetoothChatService.STATE_NONE:
    242.                     mTitle.setText(R.string.title_not_connected);
    243.                     break;
    244.                 }
    245.                 break;
    246.             case MESSAGE_WRITE:
    247.                 Log.i(TAG , "writing case");
    248.                 byte[] writeBuf = (byte[]) msg.obj;
    249.                 // construct a string from the buffer
    250.                 String writeMessage = new String(writeBuf);
    251.                 mConversationArrayAdapter.add("Me:  " + writeMessage);
    252.                 break;
    253.             case MESSAGE_READ:
    254.                 Log.i(TAG, "reading case");
    255.                 byte[] readBuf = (byte[]) msg.obj;
    256.                 // construct a string from the valid bytes in the buffer
    257.                 String readMessage = new String(readBuf, 0, msg.arg1);
    258.                 mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
    259.                 break;
    260.             case MESSAGE_DEVICE_NAME:
    261.                 // save the connected device's name
    262.                 mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
    263.                 Toast.makeText(getApplicationContext(), "Connected to "
    264.                                + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
    265.                 break;
    266.             case MESSAGE_TOAST:
    267.                 Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
    268.                                Toast.LENGTH_SHORT).show();
    269.                 break;
    270.             }
    271.         }
    272.     };
    273.  
    274.     public void onActivityResult(int requestCode, int resultCode, Intent data) {
    275.         if(D) Log.d(TAG, "onActivityResult " + resultCode);
    276.         switch (requestCode) {
    277.         case REQUEST_CONNECT_DEVICE_SECURE:
    278.             // When DeviceListActivity returns with a device to connect
    279.             if (resultCode == Activity.RESULT_OK) {
    280.                 connectDevice(data, true);
    281.             }
    282.             break;
    283.         case REQUEST_CONNECT_DEVICE_INSECURE:
    284.             // When DeviceListActivity returns with a device to connect
    285.             if (resultCode == Activity.RESULT_OK) {
    286.                 connectDevice(data, false);
    287.             }
    288.             break;
    289.         case REQUEST_ENABLE_BT:
    290.             // When the request to enable Bluetooth returns
    291.             if (resultCode == Activity.RESULT_OK) {
    292.                 // Bluetooth is now enabled, so set up a chat session
    293.                 setupChat();
    294.             } else {
    295.                 // User did not enable Bluetooth or an error occured
    296.                 Log.d(TAG, "BT not enabled");
    297.                 Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
    298.                 finish();
    299.             }
    300.         }
    301.     }
    302.  
    303.     private void connectDevice(Intent data, boolean secure) {
    304.         // Get the device MAC address
    305.         String address = data.getExtras()
    306.             .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
    307.         // Get the BLuetoothDevice object
    308.         BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    309.         // Attempt to connect to the device
    310.         mChatService.connect(device, secure);
    311.     }
    312.  
    313.     @Override
    314.     public boolean onCreateOptionsMenu(Menu menu) {
    315.         MenuInflater inflater = getMenuInflater();
    316.         inflater.inflate(R.menu.option_menu, menu);
    317.         return true;
    318.     }
    319.  
    320.     @Override
    321.     public boolean onOptionsItemSelected(MenuItem item) {
    322.         Intent serverIntent = null;
    323.         switch (item.getItemId()) {
    324.         case R.id.secure_connect_scan:
    325.             // Launch the DeviceListActivity to see devices and do scan
    326.             serverIntent = new Intent(this, DeviceListActivity.class);
    327.             startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
    328.             return true;
    329.         case R.id.insecure_connect_scan:
    330.             // Launch the DeviceListActivity to see devices and do scan
    331.             serverIntent = new Intent(this, DeviceListActivity.class);
    332.             startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
    333.             return true;
    334.         case R.id.discoverable:
    335.             // Ensure this device is discoverable by others
    336.             ensureDiscoverable();
    337.             return true;
    338.         }
    339.         return false;
    340.     }
    341.  
    342. }
    343.  
    This handles the chat...

    Code (Text):
    1.  
    2. package com.example.android.BluetoothChat;
    3.  
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.io.OutputStream;
    7. import java.util.UUID;
    8.  
    9. import android.bluetooth.BluetoothAdapter;
    10. import android.bluetooth.BluetoothDevice;
    11. import android.bluetooth.BluetoothServerSocket;
    12. import android.bluetooth.BluetoothSocket;
    13. import android.content.Context;
    14. import android.os.Bundle;
    15. import android.os.Handler;
    16. import android.os.Message;
    17. import android.util.Log;
    18.  
    19. /**
    20.  * This class does all the work for setting up and managing Bluetooth
    21.  * connections with other devices. It has a thread that listens for
    22.  * incoming connections, a thread for connecting with a device, and a
    23.  * thread for performing data transmissions when connected.
    24.  */
    25. public class BluetoothChatService {
    26.     // Debugging
    27.     private static final String TAG = "BluetoothChatService";
    28.     private static final boolean D = true;
    29.  
    30.     // Name for the SDP record when creating server socket
    31.     private static final String NAME_SECURE = "BluetoothChatSecure";
    32.     private static final String NAME_INSECURE = "BluetoothChatInsecure";
    33.  
    34.     // Unique UUID for this application
    35.     private static final UUID MY_UUID_SECURE =
    36.         UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    37.     private static final UUID MY_UUID_INSECURE =
    38.         UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    39.  
    40.     // Member fields
    41.     private final BluetoothAdapter mAdapter;
    42.     private final Handler mHandler;
    43.     private AcceptThread mSecureAcceptThread;
    44.     private AcceptThread mInsecureAcceptThread;
    45.     private ConnectThread mConnectThread;
    46.     private ConnectedThread mConnectedThread;
    47.     private int mState;
    48.  
    49.     // Constants that indicate the current connection state
    50.     public static final int STATE_NONE = 0;       // we're doing nothing
    51.     public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    52.     public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    53.     public static final int STATE_CONNECTED = 3;  // now connected to a remote device
    54.  
    55.     /**
    56.      * Constructor. Prepares a new BluetoothChat session.
    57.      * @param context  The UI Activity Context
    58.      * @param handler  A Handler to send messages back to the UI Activity
    59.      */
    60.     public BluetoothChatService(Context context, Handler handler) {
    61.         mAdapter = BluetoothAdapter.getDefaultAdapter();
    62.         mState = STATE_NONE;
    63.         mHandler = handler;
    64.     }
    65.  
    66.     /**
    67.      * Set the current state of the chat connection
    68.      * @param state  An integer defining the current connection state
    69.      */
    70.     private synchronized void setState(int state) {
    71.         if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
    72.         mState = state;
    73.  
    74.         // Give the new state to the Handler so the UI Activity can update
    75.         mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    76.     }
    77.  
    78.     /**
    79.      * Return the current connection state. */
    80.     public synchronized int getState() {
    81.         return mState;
    82.     }
    83.  
    84.     /**
    85.      * Start the chat service. Specifically start AcceptThread to begin a
    86.      * session in listening (server) mode. Called by the Activity onResume() */
    87.     public synchronized void start() {
    88.         if (D) Log.d(TAG, "start");
    89.  
    90.         // Cancel any thread attempting to make a connection
    91.         if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
    92.  
    93.         // Cancel any thread currently running a connection
    94.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
    95.  
    96.         setState(STATE_LISTEN);
    97.  
    98.         // Start the thread to listen on a BluetoothServerSocket
    99.         if (mSecureAcceptThread == null) {
    100.             mSecureAcceptThread = new AcceptThread(true);
    101.             mSecureAcceptThread.start();
    102.         }
    103.         if (mInsecureAcceptThread == null) {
    104.             mInsecureAcceptThread = new AcceptThread(false);
    105.             mInsecureAcceptThread.start();
    106.         }
    107.     }
    108.  
    109.     /**
    110.      * Start the ConnectThread to initiate a connection to a remote device.
    111.      * @param device  The BluetoothDevice to connect
    112.      * @param secure Socket Security type - Secure (true) , Insecure (false)
    113.      */
    114.     public synchronized void connect(BluetoothDevice device, boolean secure) {
    115.         if (D) Log.d(TAG, "connect to: " + device);
    116.  
    117.         // Cancel any thread attempting to make a connection
    118.         if (mState == STATE_CONNECTING) {
    119.             if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
    120.         }
    121.  
    122.         // Cancel any thread currently running a connection
    123.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
    124.  
    125.         // Start the thread to connect with the given device
    126.         mConnectThread = new ConnectThread(device, secure);
    127.         mConnectThread.start();
    128.         setState(STATE_CONNECTING);
    129.     }
    130.  
    131.     /**
    132.      * Start the ConnectedThread to begin managing a Bluetooth connection
    133.      * @param socket  The BluetoothSocket on which the connection was made
    134.      * @param device  The BluetoothDevice that has been connected
    135.      */
    136.     public synchronized void connected(BluetoothSocket socket, BluetoothDevice
    137.             device, final String socketType) {
    138.         if (D) Log.d(TAG, "connected, Socket Type:" + socketType);
    139.  
    140.         // Cancel the thread that completed the connection
    141.         if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
    142.  
    143.         // Cancel any thread currently running a connection
    144.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
    145.  
    146.         // Cancel the accept thread because we only want to connect to one device
    147.         if (mSecureAcceptThread != null) {
    148.             mSecureAcceptThread.cancel();
    149.             mSecureAcceptThread = null;
    150.         }
    151.         if (mInsecureAcceptThread != null) {
    152.             mInsecureAcceptThread.cancel();
    153.             mInsecureAcceptThread = null;
    154.         }
    155.  
    156.         // Start the thread to manage the connection and perform transmissions
    157.         mConnectedThread = new ConnectedThread(socket, socketType);
    158.         mConnectedThread.start();
    159.  
    160.         // Send the name of the connected device back to the UI Activity
    161.         Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
    162.         Bundle bundle = new Bundle();
    163.         bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
    164.         msg.setData(bundle);
    165.         mHandler.sendMessage(msg);
    166.  
    167.         setState(STATE_CONNECTED);
    168.     }
    169.  
    170.     /**
    171.      * Stop all threads
    172.      */
    173.     public synchronized void stop() {
    174.         if (D) Log.d(TAG, "stop");
    175.  
    176.         if (mConnectThread != null) {
    177.             mConnectThread.cancel();
    178.             mConnectThread = null;
    179.         }
    180.  
    181.         if (mConnectedThread != null) {
    182.             mConnectedThread.cancel();
    183.             mConnectedThread = null;
    184.         }
    185.  
    186.         if (mSecureAcceptThread != null) {
    187.             mSecureAcceptThread.cancel();
    188.             mSecureAcceptThread = null;
    189.         }
    190.  
    191.         if (mInsecureAcceptThread != null) {
    192.             mInsecureAcceptThread.cancel();
    193.             mInsecureAcceptThread = null;
    194.         }
    195.         setState(STATE_NONE);
    196.     }
    197.  
    198.     /**
    199.      * Write to the ConnectedThread in an unsynchronized manner
    200.      * @param out The bytes to write
    201.      * @see ConnectedThread#write(byte[])
    202.      */
    203.     public void write(byte[] out) {
    204.         // Create temporary object
    205.         ConnectedThread r;
    206.         // Synchronize a copy of the ConnectedThread
    207.         synchronized (this) {
    208.             if (mState != STATE_CONNECTED) return;
    209.             r = mConnectedThread;
    210.         }
    211.         // Perform the write unsynchronized
    212.         r.write(out);
    213.     }
    214.  
    215.     /**
    216.      * Indicate that the connection attempt failed and notify the UI Activity.
    217.      */
    218.     private void connectionFailed() {
    219.         // Send a failure message back to the Activity
    220.         Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    221.         Bundle bundle = new Bundle();
    222.         bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
    223.         msg.setData(bundle);
    224.         mHandler.sendMessage(msg);
    225.  
    226.         // Start the service over to restart listening mode
    227.         BluetoothChatService.this.start();
    228.     }
    229.  
    230.     /**
    231.      * Indicate that the connection was lost and notify the UI Activity.
    232.      */
    233.     private void connectionLost() {
    234.         // Send a failure message back to the Activity
    235.         Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    236.         Bundle bundle = new Bundle();
    237.         bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
    238.         msg.setData(bundle);
    239.         mHandler.sendMessage(msg);
    240.  
    241.         // Start the service over to restart listening mode
    242.         BluetoothChatService.this.start();
    243.     }
    244.  
    245.     /**
    246.      * This thread runs while listening for incoming connections. It behaves
    247.      * like a server-side client. It runs until a connection is accepted
    248.      * (or until cancelled).
    249.      */
    250.     private class AcceptThread extends Thread {
    251.         // The local server socket
    252.         private final BluetoothServerSocket mmServerSocket;
    253.         private String mSocketType;
    254.  
    255.         public AcceptThread(boolean secure) {
    256.             BluetoothServerSocket tmp = null;
    257.             mSocketType = secure ? "Secure":"Insecure";
    258.  
    259.             // Create a new listening server socket
    260.             try {
    261.                 if (secure) {
    262.                     tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
    263.                         MY_UUID_SECURE);
    264.                 } else {
    265.                     tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
    266.                             NAME_INSECURE, MY_UUID_INSECURE);
    267.                 }
    268.             } catch (IOException e) {
    269.                 Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
    270.             }
    271.             mmServerSocket = tmp;
    272.         }
    273.  
    274.         public void run() {
    275.             if (D) Log.d(TAG, "Socket Type: " + mSocketType +
    276.                     "BEGIN mAcceptThread" + this);
    277.             setName("AcceptThread" + mSocketType);
    278.  
    279.             BluetoothSocket socket = null;
    280.  
    281.             // Listen to the server socket if we're not connected
    282.             while (mState != STATE_CONNECTED) {
    283.                 try {
    284.                     // This is a blocking call and will only return on a
    285.                     // successful connection or an exception
    286.                     socket = mmServerSocket.accept();
    287.                 } catch (IOException e) {
    288.                     Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
    289.                     break;
    290.                 }
    291.  
    292.                 // If a connection was accepted
    293.                 if (socket != null) {
    294.                     synchronized (BluetoothChatService.this) {
    295.                         switch (mState) {
    296.                         case STATE_LISTEN:
    297.                         case STATE_CONNECTING:
    298.                             // Situation normal. Start the connected thread.
    299.                             connected(socket, socket.getRemoteDevice(),
    300.                                     mSocketType);
    301.                             break;
    302.                         case STATE_NONE:
    303.                         case STATE_CONNECTED:
    304.                             // Either not ready or already connected. Terminate new socket.
    305.                             try {
    306.                                 socket.close();
    307.                             } catch (IOException e) {
    308.                                 Log.e(TAG, "Could not close unwanted socket", e);
    309.                             }
    310.                             break;
    311.                         }
    312.                     }
    313.                 }
    314.             }
    315.             if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);
    316.  
    317.         }
    318.  
    319.         public void cancel() {
    320.             if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
    321.             try {
    322.                 mmServerSocket.close();
    323.             } catch (IOException e) {
    324.                 Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
    325.             }
    326.         }
    327.     }
    328.  
    329.  
    330.     /**
    331.      * This thread runs while attempting to make an outgoing connection
    332.      * with a device. It runs straight through; the connection either
    333.      * succeeds or fails.
    334.      */
    335.     private class ConnectThread extends Thread {
    336.         private final BluetoothSocket mmSocket;
    337.         private final BluetoothDevice mmDevice;
    338.         private String mSocketType;
    339.  
    340.         public ConnectThread(BluetoothDevice device, boolean secure) {
    341.             mmDevice = device;
    342.             BluetoothSocket tmp = null;
    343.             mSocketType = secure ? "Secure" : "Insecure";
    344.  
    345.             // Get a BluetoothSocket for a connection with the
    346.             // given BluetoothDevice
    347.             try {
    348.                 if (secure) {
    349.                     tmp = device.createRfcommSocketToServiceRecord(
    350.                             MY_UUID_SECURE);
    351.                 } else {
    352.                     tmp = device.createInsecureRfcommSocketToServiceRecord(
    353.                             MY_UUID_INSECURE);
    354.                 }
    355.             } catch (IOException e) {
    356.                 Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    357.             }
    358.             mmSocket = tmp;
    359.         }
    360.  
    361.         public void run() {
    362.             Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
    363.             setName("ConnectThread" + mSocketType);
    364.  
    365.             // Always cancel discovery because it will slow down a connection
    366.             mAdapter.cancelDiscovery();
    367.  
    368.             // Make a connection to the BluetoothSocket
    369.             try {
    370.                 // This is a blocking call and will only return on a
    371.                 // successful connection or an exception
    372.                 mmSocket.connect();
    373.             } catch (IOException e) {
    374.                 // Close the socket
    375.                 try {
    376.                     mmSocket.close();
    377.                 } catch (IOException e2) {
    378.                     Log.e(TAG, "unable to close() " + mSocketType +
    379.                             " socket during connection failure", e2);
    380.                 }
    381.                 connectionFailed();
    382.                 return;
    383.             }
    384.  
    385.             // Reset the ConnectThread because we're done
    386.             synchronized (BluetoothChatService.this) {
    387.                 mConnectThread = null;
    388.             }
    389.  
    390.             // Start the connected thread
    391.             connected(mmSocket, mmDevice, mSocketType);
    392.         }
    393.  
    394.         public void cancel() {
    395.             try {
    396.                 mmSocket.close();
    397.             } catch (IOException e) {
    398.                 Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
    399.             }
    400.         }
    401.     }
    402.  
    403.     /**
    404.      * This thread runs during a connection with a remote device.
    405.      * It handles all incoming and outgoing transmissions.
    406.      */
    407.     private class ConnectedThread extends Thread {
    408.         private final BluetoothSocket mmSocket;
    409.         private final InputStream mmInStream;
    410.         private final OutputStream mmOutStream;
    411.  
    412.         public ConnectedThread(BluetoothSocket socket, String socketType) {
    413.             Log.d(TAG, "create ConnectedThread: " + socketType);
    414.             mmSocket = socket;
    415.             InputStream tmpIn = null;
    416.             OutputStream tmpOut = null;
    417.  
    418.             // Get the BluetoothSocket input and output streams
    419.             try {
    420.                 tmpIn = socket.getInputStream();
    421.                 tmpOut = socket.getOutputStream();
    422.             } catch (IOException e) {
    423.                 Log.e(TAG, "temp sockets not created", e);
    424.             }
    425.            
    426.  
    427.             mmInStream = tmpIn;
    428.             mmOutStream = tmpOut;
    429.            
    430.            
    431.         }
    432.  
    433.         public void run() {
    434.            
    435.              Log.i(TAG, "BEGIN mConnectedThread");
    436.              byte[] buffer1 = new byte[1024];
    437.              int bytes;
    438.  
    439.              // Keep listening to the InputStream while connected
    440.            //  Log.e(TAG, "Reading");
    441.              while (true) {
    442.                  try {
    443.                      // Read from the InputStream
    444.                      Log.e(TAG, "Reading");
    445.                      bytes = mmInStream.read(buffer1);
    446.  
    447.                      // Send the obtained bytes to the UI Activity
    448.                      
    449.                  } catch (IOException e) {
    450.                      Log.e(TAG, "disconnected", e);
    451.                      connectionLost();
    452.                      break;
    453.                  }
    454.                  mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, 0, buffer1)
    455.                  .sendToTarget();
    456.              }
    457.            
    458.         }
    459.  
    460.         /**
    461.          * Write to the connected OutStream.
    462.          * @param buffer  The bytes to write
    463.          */
    464.         public void write(byte[] buffer) {
    465.             try {
    466.                 Log.e(TAG, "Writing");
    467.                 mmOutStream.write(buffer);
    468.  
    469.                 // Share the sent message back to the UI Activity
    470.                 mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, 0, 0, buffer)
    471.                         .sendToTarget();
    472.             } catch (IOException e) {
    473.                 Log.e(TAG, "Exception during write", e);
    474.             }
    475.         }
    476.  
    477.         public void cancel() {
    478.             try {
    479.                 mmSocket.close();
    480.             } catch (IOException e) {
    481.                 Log.e(TAG, "close() of connect socket failed", e);
    482.             }
    483.         }
    484.     }
    485. }

    Any Ideas at all?

    tl;dr - BluetoothChat sample app seems to simply regurgitate the data I try to write to the output stream - I am recieving data from the client but am unable to send it information

    Advertisement
    :
Loading...

Share This Page