Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: UI hangs while sending data on bluetooth.

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default UI hangs while sending data on bluetooth.

    Hello All,

    This is my first post to this forum. I am new to android development. I am trying to write a client application which talk to server application via bluetooth. Server application is running on embedded platfrom.

    I referred bluetoothchat example for bluetooth data transfer. In my application I have two activities, Main activity shows list of bluetooth devices and when a user clicks on one of the devices it will open a new activity. Then it will open a bluetooth socket start thread to connect to server. I have a message handler which talks to the connected thread.

    my codes looks like this
    1protected static final int SUCCESS_CONNECT = 0;
    2	protected static final int MESSAGE_READ = 1;
    3	protected static final int RECIEVE_MESSAGE = 2; // Status for Handler
    4 public BluetoothSocket mmSocket;
    5 public InputStream mmInStream;
    6 public OutputStream mmOutStream;
    7	String tag = "debugging";
    8	
    9	private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    10	Handler mHandler = new Handler(){
    11	@Override
    12	public void handleMessage(Message msg)
    13	{
    14	// TODO Auto-generated method stub
    15	Log.i(tag, "in handler");
    16	super.handleMessage(msg);
    17	switch(msg.what){
    18	case SUCCESS_CONNECT:
    19	// DO something
    20	ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
    21	//Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
    22	String s = "successfully connected";
    23	//connectedThread.write(s.getBytes());
    24	connectedThread.write(s.getBytes());
    25	Log.i(tag, "connected");
    26	break;
    27	case MESSAGE_READ:
    28	byte[] readBuf = (byte[])msg.obj;
    29	//String string = new String(readBuf, 0, msg.arg1);
    30	Toast.makeText(getApplicationContext(), "Test", 0).show();
    31	// Create the text view
    32	//TextView textView = (TextView)findViewById(R.id.rcvedMsg);
    33	//textView.setTextSize(40);
    34	//textView.setText(string);
    35	break;
    36	case RECIEVE_MESSAGE:
    37	byte[] readmsgBuf = (byte[])msg.obj;
    38	String string = new String(readmsgBuf, 0, msg.arg1);
    39	Toast.makeText(getApplicationContext(), "Test", 0).show();
    40	// Create the text view
    41	//TextView textView = (TextView)findViewById(R.id.rcvedMsg);
    42	//textView.setTextSize(40);
    43	//textView.setText(string);
    44	break;
    45	}
    46	}


    private class ConnectedThread extends Thread
    2	{
    3	public ConnectedThread(BluetoothSocket socket)
    4	{
    5	mmSocket = socket;
    6	InputStream tmpIn = null;
    7	OutputStream tmpOut = null;
    8	
    9	// Get the input and output streams, using temp objects because
    10	// member streams are final
    11	try {
    12	tmpIn = socket.getInputStream();
    13	tmpOut = socket.getOutputStream();
    14	} catch (IOException e) { }
    15	
    16	mmInStream = tmpIn;
    17	mmOutStream = tmpOut;
    18	}
    19	
    20	public void run() {
    21	byte[] buffer ; // buffer store for the stream
    22	int bytes; // bytes returned from read()
    23
    24	// Keep listening to the InputStream until an exception occurs
    25	while (true) {
    26	try {
    27	// Read from the InputStream
    28	buffer = new byte[1024];
    29	bytes = mmInStream.read(buffer);
    30	Log.d("MR", "input stream :"+(new String(buffer)));
    31	// Send the obtained bytes to the UI activity
    32	mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
    33	} catch (IOException e) {
    34	break;
    35	}
    36	}
    37	}
    38	
    39	/* Call this from the main activity to send data to the remote device */
    40	public void write(byte[] bytes) {
    41	try {
    42	//a delay of 20ms occurs after each flush...
    43	mmOutStream.write(bytes);
    44	mmOutStream.flush();
    45	} catch (IOException e) { }
    46	}
    47	
    48	/* Call this from the main activity to shutdown the connection */
    49	public void cancel() {
    50	try {
    51	mmSocket.close();
    52	} catch (IOException e) { }
    53	}
    54	}

    method to write to data to bluetooth on pressing a button.
    1public void ledOff(View v ) throws IOException
    2	{
    3	//Toast.makeText(getApplicationContext(),"LED OFF", 0).show();
    4/* if (mmSocket != null)
    5	try {
    6	mmSocket.getOutputStream().write('f');
    7	} catch (IOException e) {
    8	// TODO Auto-generated catch block
    9	e.printStackTrace();
    10	}
    11*/
    12	if(mmOutStream != null)
    13	{
    14	mmOutStream.write('f');
    15	}
    16	}


    Some times my UI hangs when I click a button, it takes ages to respond back. In my method for ledOn I call bluetooth input stream. Is this correct method to do it.

    Can some one please share some views on this.
    Thanks


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: UI hangs while sending data on bluetooth.

    Any reason you are using Threads and not AsyncTasks? Trust me, AsyncTasks are a million times easier to manage than conventional threading: AsyncTask | Android Developers
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: UI hangs while sending data on bluetooth.

    Hi Aussiemcgr,

    Thanks for your reply, I am new to android development so I started with bluetooth chat example which is based on threads.

    I guess I should read more about threads and AsyncTask. I noticed one more thing the problem which I mentioned earlier happens randomly. If i restart the tablet then i dont see this problem. Could it be that if my application crashed earlier it didnt close the threads and bluetooth sockets.

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: UI hangs while sending data on bluetooth.

    Check the log for error messages

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: UI hangs while sending data on bluetooth.

    Tama, I remember the issues we had trying to manage multithreading on an android device. It is a bit more hands-on than other java development. My guess is that you were modifying the UI from the Bluetooth thread, which I believe forces a thread sync if you don't handle the multithreading properly. That sync would result in the UI thread hanging. If done properly, AsyncTask seems to handle all of that for you without forcing a thread sync.

    For those not doing Android development, I also recently found a newish class in the Java Swing library which handles multithreading for non-Android java swing application. The SwingWorker class seems to handle multithreading in desktop applications with similar ease as Android's AsyncTask.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. #6
    Junior Member
    Join Date
    Aug 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: UI hangs while sending data on bluetooth.

    Thanks your comments Aussiemcgr. Sorry for delayed reply i was writting the application for the embedded device which interacts with the tablet via bluetooth. It seems that from the UI thread i am sending bluetooth data, bluetooth is running a different thread, hence its kind of messing thing. I am going to give AsyncTask a try.

Similar Threads

  1. Replies: 2
    Last Post: July 9th, 2013, 06:01 PM
  2. [Asking] Sending and Receiving Data via Serial
    By ardisamudra in forum Java Networking
    Replies: 5
    Last Post: January 23rd, 2013, 06:24 AM
  3. Sending data too fast
    By polyfrag in forum Java Networking
    Replies: 1
    Last Post: August 10th, 2012, 04:28 PM
  4. BufferedReader hangs when handling POST method data
    By Sucker Punch in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 28th, 2012, 04:33 PM
  5. Sending Data Between PC to Mobile
    By ultrabeat in forum Java Theory & Questions
    Replies: 0
    Last Post: July 23rd, 2011, 09:06 AM