Android

Android Thread Example, UIThread example

Using Android API Level : 7 

[tags] Android Thread Example, Android Long Running Activity, Android Long Thread, Android [/tags]

Author: Ishtek
Date: 07/April/2014

Just a quick question from Author, before actually we start going over this write-up.

Have you ever got an error on screen while running a piece of code/logic for some long time,
while developing an application to run on Android Platform.

If yes, then you are going to read and know the probable reason for this behavior.
This could be an example of a long running activity, and in this writing, we are going to
explore a hypothetical scenario. Let us create a simple application with a single activity
and code a for loop for iterating for 100 times with 1 second timegap/interval.

Following source code is the main activity of this example:

package net.techiecommunity.demothread; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ThreadDemoActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_demo); final TextView txtView = (TextView) findViewById(R.id.textView1); Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { txtView.setText("Processing..."); for(int i=0; i<100; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } txtView.setText("Completed.. 100%"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_thread_demo, menu); return true; } }
If this activity is running inside Emulator, then we can observe the main screen:

First/Main screen.

On clicking button, not showing Processing.. text

After for loop execution, Completed text is shown.
package net.techiecommunity.demothread; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ThreadDemoActivity extends Activity { private int i = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_demo); final TextView txtView = (TextView) findViewById(R.id.textView1); Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { //A new thread is created for running the counter from 1 to 100. new Thread(new Runnable() { public void run() { for (i = 0; i <= 100; i++) { try { if (i <= 99) { //Used post method for the view by passing a separate runnable for //passing text to the UI element. txtView.post(new Runnable() { public void run() { txtView.setText("Processing... " + i + "%"); } }); } else { txtView.post(new Runnable() { public void run() { txtView.setText("Completed.. 100%"); } }); } Thread.sleep(1000); } catch (InterruptedException e) { } } } }).start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_thread_demo, menu); return true; } }
By using above code, and if everything is done as required, then following are the images as shown below:

First/Main screen.

On clicking button, now showing Processing.. text

After for loop execution, Completed text is shown.
Above example is using 'view.post()' method with a separate runnable instance for pushing value/data to UI element. There are other ways to achieve this are : View.postDelayed(Runnable, long) and Activity.runOnUiThread(Runnable). postDelayed(Runnable, long) can be used for scenarios where the runnable code is desired to be started after certain time elapsed, as per the long typed argument parameter in this method. Activity.runOnUiThread(Runnable), as the method name suggests, runnable code is to run in UI thread. I have modified above code with runOnUiThread method, as follows:
for (i = 0; i <= 100; i++) { try { if (i <= 99) { runOnUiThread(new Runnable() { public void run() { txtView.setText("Processing... " + i + "%"); } }); } else { runOnUiThread(new Runnable() { public void run() { txtView.setText("Completed.. 100%"); } }); } Thread.sleep(1000); } catch (InterruptedException e) { } }
If interested in commenting related to Android Thread Example
Click Here

Name (To be shown on this Page:*

Email (Not to be shown):*

Website (To be shown on this Page)

Your Comments here (To be shown on this Page):*

(You can use <a> Tag in your comments)

Please enter same number as shown here 926

Name: RameshDated: 2014-04-07 19:14:40
Thanks for this example.

I am just wondering how to handle/code for receiving
callback from a long running task
that gets over and the main/UI thread would react only after it receives a callback on completion.
    
Name: Ishtek (Author of this Page)Dated: 2014-04-07 19:19:01
Hello,

In this particular scenario that you require to have some ways to get a callback from the 
task running in background, then I think you can explore AsyncTask API, and there would be callback
methods, and onPostExecute can be used to do certain operations on completion of the the long
running task in background thread.

Hope this helps.
Reply
Click Here

Name (To be shown on Page):*

Email (Optional): (never shown)

Website (To be shown on this Page)

Your Comments here (To be shown on Page):*

Please enter same number as shown here 963




Android Thread Example

REST Interview Questions

JAX-WS Webservice Example

Android Overlap SurfaceView Example

Spring3 Integration of File Endpoint

JAXWS Webservice Example

Android WebView Example

Android Context Menu Example

Setting up Eclipse for Android App Development

Android SensorEvent Orientation Example

Android ImageSwitcher Example

REST API Design for Android App

Android ExpandableListView Example

Singleton Serializable on Android

Android GPS with Google MAP Example

Android Project With Example

Android Project Manageing Files

Project Ideas for App on Android Platform

Android EditText with Background

Android SQLite Database Example

Android AutoCompleteTextView Example

Android Tester

Android Interview Questions

Android ListView Example

Android Intent Notification Example

Android Intent Broadcast Example

Android TextView Link Example

Android Sensor List

Android Sensor Orientation Example

Android Intent Broadcast Receiver

Android Gallery SurfaceViews Example

Android Location Example

Android Text to Speech Example

Android Intent Example

Android Layout Example

Android Download File Example

Android Expandable ListView Example

Android Tab Example

Android RelativeLayout Example

Android Intent Example

Android Text to Speech Example

Android SQLite Example

Android CustomView Example

Android Canvas Example

Android SharedPreferences Example

Android Shape Background Example

Android ShapeButton Example

Android ViewFlipper Example

Android Gallery Example

Android TimePickerDialog Example





If interested commenting on this Page :

comments powered by Disqus
Any source code found on any of the page(s) in Techiecommunity.net is associated with following notice: 
   /*
     * TECHIECOMMUNITY.NET MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
     * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
     * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
     * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. TECHIECOMMUNITY.NET SHALL NOT BE LIABLE FOR
     * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
     * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
     *
     * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
     * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
     * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
     * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
     * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
     * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
     * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). TECHIECOMMUNITY.NET
     * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
     * HIGH RISK ACTIVITIES.
     */
   
The content provided in this page is NOT warranted and/or NOT guaranteed by techiecommunity.net .
techiecommunity.net is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

For any of the content, if you would like to bring it to notice for removal from this web site, 
please write to this web site administrator @ EMAIL-ID (please remove space before and after @),
with appropriate concern and supporting proof(s). After thorough review and if found genuine concern,
we would take appropriate action and remove disputed content from this web site within 24 hours 
starting from the time it has brought to techiecommunity.net Administrator notice.

This website uses cookies and third party cookies to improve the user experience. 
And to provide more relevant ads. 
In case of continued use of this website implies that you accept the use of cookies on this website.
		
While using this web site, you agree to have read and accepted techiecommunity.net terms of use and privacy policy.