Code:
Package Com.test.handler; Import COM.TEST.DEMO.R; Import Android.app.activity;import android.app.progressdialog;import Android.os.asynctask;import android.os.Bundle ; import Android.view.menu;import Android.view.menuitem;import Android.widget.TextView; public class Asynctasktestactivity extends Activity {private TextView TextView; Private ProgressDialog Dialog; Counter is used to save intermediate results private class Counter {public int progress; public int sum; public Counter (int progress, int sum) {this.progress = progress; This.sum = sum; }}//define the Asynctask subclass, pass the parameter void to the task, process the intermediate result type to counter type, and process the end result to the integer type private class MyTask extends Asynctask<vo ID, Counter, integer> {@Override protected void OnPreExecute () {//TODO auto-generated Metho D stub Super.onpreexecute (); Textview.settext ("result:0"); Dialog.show (); } @Override protected Integer doinBackground (Void ... params) {int sum = 0; try {for (int i = 0; i <; i++) {sum + = i * 2; The intermediate result is published, and the Onprogressupdate function processes the intermediate result, which displays the progress publishprogress (new Counter (i, Sum) on the UI component); Thread.Sleep (40); }} catch (Exception e) {//Todo:handle Exception e.printstacktrace (); }//Returns the final processing result return integer.valueof (sum); } @Override protected void Onprogressupdate (Counter ... values) {//Intermediate result processing: Set progress bar, show current accumulation on TextView Results of dialog.setprogress (values[0].progress); Textview.settext ("Result:" + values[0].sum); }//Doinbackground execution @Override protected void OnPostExecute (Integer result) after processing is complete { Super.onpostexecute (result); Dialog.dismiss (); Textview.settext ("Result:" + result); }} @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestat e); Setcontentview (R.LAYOUT.ACTIVITY_HANDLER_TEST2); dialog = new ProgressDialog (this); Dialog.settitle ("Start"); Dialog.seticon (R.drawable.ic_dialog_load); Dialog.setmessage ("Please Wait"); Dialog.setmax (100); Dialog.setprogress (0); Dialog.setindeterminate (FALSE); Dialog.setprogressstyle (progressdialog.style_horizontal); Dialog.setcancelable (FALSE); TextView = (TextView) Findviewbyid (R.ID.RESULT2); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the ACTI On bar if it is present. Getmenuinflater (). Inflate (R.menu.handler_test2, menu); return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action Bar would//AutomaticallY handle clicks on the Home/up button, so long/As you specify a parent activity in Androidmanifest.xml. int id = item.getitemid (); if (id = = r.id.action_settings) {return true; } else if (id = = R.ID.ACTION_REFLASH2) {//Start task, each time you create a new Task Object MyTask (). Execute (); return true; } return super.onoptionsitemselected (item); } }
Layout file:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin " android:paddingright=" @dimen/activity_horizontal_margin " android:paddingtop=" @dimen /activity_vertical_margin " tools:context=" com.test.handler.AsyncTaskTestActivity "> <textview android:id= "@+id/result2" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content " android:text=" @string/hello_world "/></relativelayout>
The rules given on Android docs:
Threading Rules
There is a few threading rules that must being followed for this class to work properly:
- The Asynctask class must is loaded on the UI thread. This is the done automatically as of
JELLY_BEAN .
- The task instance must is created on the UI thread.
execute(Params...)Must is invoked on the UI thread.
- Don't call
onPreExecute() ,, onPostExecute(Result) doInBackground(Params...) , onProgressUpdate(Progress...) manually.
- The task can be executed only once (an exception would be thrown if a second execution is attempted.)
Android Note--asynctask Example