/** * Three generic parameters for an asynchronous task: * 1, the parameter type passed in when the Execute method is called, input parameter * 2, progressupdate method into parameter * 3, return type of the return result type of the asynchronous task Doinbackground, Dopostexecute of the method of use * * * Some Considerations for using asynchronous Tasks * 1, an asynchronous task can only be executed once, more than once, will run out of exception * 2, must be created in the UI thread example of an asynchronous task * 3, you must call the Execute method in the UI thread * * public class Asynctasktest extends Activity {private TextView tv_show; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_async_task_test); Initialize View Control Tv_show = (TextView) Findviewbyid (r.id.tv_show); }/** * Start asynchronous Task * @param view */public void StartAsyncTask (view view) throws Exception {Download Asynctask asynctask = new Downloadasynctask (this); Asynctask.execute (New URL ("http://baidu.com")); } public class Downloadasynctask extends asynctask<url,integer,void>{private Context mcontext; Private ProgressDialog progressdialog = null; Public Downloadasynctask (Context context) { This.mcontext = context; }/** * Start the background task before execution, * generally do some initialization work, such as: Initialization dialog box */@Override protected void Onpre Execute () {progressdialog = new ProgressDialog (mcontext); Progressdialog.settitle ("In-mission execution"); Progressdialog.setmessage ("The task is executing, please wait patiently ..."); Sets the user cannot cancel the progress bar dialog box progressdialog.setcancelable (false); Progressdialog.setmax (100); Progressdialog.setprogressstyle (progressdialog.style_horizontal); Progressdialog.show (); /** * Perform background tasks * @param params * @return */@Override protected Void Doinbackground (URL ... params) {int i = 1; for (; i < i++) {try {thread.sleep (300); } catch (Interruptedexception e) {e.printstacktrace (); } publishprogress (i); }return null; }/** * Update progress information * @param values */@Override protected void Onprogressupdate (I Nteger. Values) {super.onprogressupdate (values); Tv_show.settext (Values[0] + ""); Progressdialog.setprogress (Values[0]); }/** * Do something after the background operation * @param aVoid */@Override protected void Onpostexecut E (Void aVoid) {super.onpostexecute (aVoid); Progressdialog.dismiss (); ProgressDialog = null; } }}
Asynchronous tasks for Android