Application not responding while performing a read/write operation on socket too frequently


In my application i have byte array of 12 digit which is used to read the status. After writing this array i am getting the status of different buttons. Based on this response i am setting up my buttons to ON|OFF. i am doing this task repeatedly.if i set this interval time too less i.e 100ms and pressing those buttons too frequently then my application is stops to respond.

Here is the code snippet.

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); getSharedSettings(); fanDimmer1=(ToggleButton)findViewById(R.id.button_fan1); fanDimmer2=(ToggleButton)findViewById(R.id.button_fan2); dimmerLight1=(ToggleButton)findViewById(R.id.button_light1); dimmerLight2=(ToggleButton)findViewById(R.id.button_light2); fanDimmer1.setOnClickListener(this); fanDimmer2.setOnClickListener(this); dimmerLight1.setOnClickListener(this); dimmerLight2.setOnClickListener(this); if(ip.equals("") || port.equals("")) { new AlertDialog.Builder(MainActivity.this) .setTitle("Warning !") .setMessage("Please set IP and PORT first") .setIcon(android.R.drawable.ic_dialog_alert) .setNeutralButton("ok", null) .show(); } else { new Thread(new Runnable() { @Override public void run() { Log.v(TAG, "openconnection"); openConnection(); } }).start(); m_handler = new Handler(); startRepeatingTask(); } } public void openConnection() { // TODO Auto-generated method stub try { s = new Socket(ip, Integer.parseInt(port)); i = s.getInputStream(); iD = new DataInputStream(i); o = s.getOutputStream(); oD = new DataOutputStream(o); Log.v(TAG, "openconnection 2"); } catch (UnknownHostException e) { // TODO: handle exception Log.v("UnknowHostException :::::", "In Catch Block"); e.printStackTrace(); } catch (IOException e) { // TODO: handle exception Log.v("IOException :::::", "In Catch Block"); e.printStackTrace(); } } Runnable m_statusChecker = new Runnable() { @Override public void run() { updateStatus(); m_handler.postDelayed(m_statusChecker,100); } private void updateStatus() { // TODO Auto-generated method stub Log.v("test", "1"); try { byte[] data1 = new byte[1024], packet1 = { (byte) 0x00,(byte) 0x00,(byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x06, (byte) 0x01,(byte) 0x01,(byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x19 }; o.write(packet1); i.read(data1, 0, 1024); byte_to_hex = ConversionMethods.bytesToHex(data1).substring(18, 26); char[] arr = byte_to_hex.toCharArray(); for (int i = 0; i < arr.length - 1; i += 2) { char temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } swapped_result=new String(arr); result = ConversionMethods.hexStringToNBitBinary(swapped_result, 32); int counter = 0; for( int i=0; i<result.length(); i++ ) { if( result.charAt(i) == '1' ) { counter++; } } status=Integer.toString(counter); txt_status.setText(status); Log.v(TAG, "status is ::"+status); char[] c=result.toCharArray(); int count=0; for (int i=0;i<result.length();i++) { count++; char j=c[i]; //Log.v(TAG, count+"::"+j); if(count==1) toggleButton=dimmerLight1; else if(count==2) toggleButton=fanDimmer2; else if(count==3) toggleButton=fanDimmer1; else if(count==4) Log.v(TAG, "Count 4 is 0"); if(j=='1') toggleButton.setChecked(true); else toggleButton.setChecked(false); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; void startRepeatingTask() { m_statusChecker.run(); } void stopRepeatingTask() { m_handler.removeCallbacks(m_statusChecker); }

And on button click i am doing this:

@Override public void onClick(View v) { if(v.equals(fanDimmer1)) { if (fanDimmer1.isChecked()) { Toast.makeText(MainActivity.this, "Fan 1 is ON", Toast.LENGTH_SHORT).show(); setByteArray((byte) 0x01, (byte) 0xff); } else { Toast.makeText(MainActivity.this, "Fan 1 is OFF", Toast.LENGTH_SHORT).show(); setByteArray((byte) 0x01, (byte) 0x00); } } }

here is <a href="http://paste.ubuntu.com/1557565/" rel="nofollow">setByteArray()</a> method i have 24 this type of buttons.

Any advice and suggestion will be appreciated.<br /> Thanks


You are calling startRepeatingTask() from your main thread:

void startRepeatingTask() { m_statusChecker.run(); }

This means that your statusChecker will runs in the main thread too.


The first thing to do is to update the code of your updateStatus method and use mHandler to post ONLY ui-update code to the main UI-thread

</li> <li>

Next you have to run the statusChecker in another thread

</li> </ul>

To do it, you have (at least) two options :


[The complex way] Do your own thread management and write something like this in your startRepeatingTask

void startRepeatingTask() { new Thread(m_statusChecker).start(); }

adapt the stop method (i.e. use a monitor, an infinite loop and a sleep)

</li> <li>

[The smart way] Take a look at <a href="http://developer.android.com/reference/java/util/Timer.html" rel="nofollow">Timer</a> and <a href="http://developer.android.com/reference/java/util/TimerTask.html" rel="nofollow">TimerTask</a> (and <a href="https://stackoverflow.com/questions/2161750/android-controlling-a-task-with-timer-and-timertask" rel="nofollow">this</a>) from the Android API and use them to implement what you need.

</li> </ol>


Focus on this code:

for (int i=0;i<result.length();i++) { count++; char j=c[i]; //Log.v(TAG, count+"::"+j); if(count==1) toggleButton=dimmerLight1; else if(count==2) toggleButton=fanDimmer2; else if(count==3) toggleButton=fanDimmer1; else if(count==4) Log.v(TAG, "Count 4 is 0"); if(j=='1') toggleButton.setChecked(true); else toggleButton.setChecked(false); }

The effect of this loop will be:

<ul><li>iteration 0 (if any) : dimmerLight1 will be checked or unchecked</li> <li>iteration 1 (if any) : fanDimmer2 will be checked or unchecked</li> <li>iteration 2 (if any) : fanDimmer1 will be checked or unchecked</li> <li>iteration 3 (if any) : fanDimmer1 will be checked or unchecked</li> <li>iteration 4 (if any) : fanDimmer1 will be checked or unchecked</li> <li>iteration 5 (if any) : fanDimmer1 will be checked or unchecked</li> <li>... (fanDimmer1 will be check or unchecked until the end of loop)</li> </ul>

I'm pretty sure this not what you need. (except if result.size() is always 3, but in any other situation: this code will produce weird things)

You can do something like this:

//assuming buttons is a ToggleButton[32] populated with all your buttons in the correct order for (int i=0;i<result.length();i++) { buttons[i].setChecked(c[i]=='1'); }


  • VerifyInputWhenFocusTarget property has no effect
  • Implementing java gui login using multithreading
  • What command do i need to pass in SabreCommandLLSRQ to get current price of PNR?
  • JSON encode and decode on PHP
  • NHibernate manually control fetching
  • Regarding starting the threads on a condition
  • Git describe fails to return most recent annotated tag
  • NSScanner Loop Question
  • SharedPreferences or SQLite Database?
  • How to determine if there are bytes available to be read from boost:asio:serial_port
  • Detect when Facebook like button is clicked
  • AJAX Html Editor Extender upload image appearing blank
  • Unity3D & Android: Difference between “UnityMain” and “main” threads?
  • NHibernate Validation Localization with S#arp Architecture
  • Ajax Loaded meta Tags
  • Get one-time binding to work for ng-if
  • Debugging ASP.NET on a built-in web server suddenly stops
  • how to do an event when i swipe from fragment to the other
  • Update CALayer sublayers immediately
  • JFileChooser in front of fullscreen Swing application
  • Spray.io: When (not) to use non-blocking route handling?
  • Volley JsonObjectRequest send headers in GET Request
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Importing jscolor library in angular 2
  • Upload files with Ajax and Jquery
  • SVN: Merging two branches together
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • python regex in pyparsing
  • JTable with a ScrollPane misbehaving
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • Android Google Maps API OnLocationChanged only called once
  • unknown Exception android
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?