Asynchronous tasks under Android

Source: Internet
Author: User

Asynchronous tasks are generally used when loading some network resources, the main implementation method is to create a new class to inherit the Asynctask of the parent class, and then make a copy of the class below some of the methods, where the Doinbackground method is necessary, see the code below

 Packagecom.example.test;ImportAndroid.os.AsyncTask;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public classProgressbarasynctaskextendsAsynctask<integer, Integer, string> {    PrivateTextView TextView; PrivateProgressBar ProgressBar;  PublicProgressbarasynctask (TextView TextView, ProgressBar ProgressBar) {Super();  This. TextView =TextView;  This. ProgressBar =ProgressBar; } @Overrideprotected voidOnPreExecute () {//In UI thread//TODO auto-generated Method Stub        Super. OnPreExecute (); Textview.settext ("OnPreExecute Start Running"); } @OverrideprotectedString doinbackground (Integer ... params) {//mainactivity passed in the parameters//TODO auto-generated Method StubNetoperatior Netoperatior =NewNetoperatior (); System.out.println ("Params" + params[0].intvalue ());//test the value passed in        inti;  for(i = ten; I <=; i + = 10) {netoperatior.operate ();//Current thread sleep 1sPublishprogress (i);//Execute onprogressupdate (Integer ... values) method        }        returni + params[0].intvalue () + ""; } @Overrideprotected voidOnPostExecute (String result) {//by Doinbackground (Integer ...//params) method to pass the value that is returned in the main UI thread .//TODO auto-generated Method Stub        Super. OnPostExecute (Result); Textview.settext ("The operation has done,the current value of I am =" +result); } @Overrideprotected voidonprogressupdate (Integer ... values) {//TODO auto-generated Method Stub        intValue = Values[0];        Progressbar.setprogress (value); Super. Onprogressupdate (values); }}

Note that the construction method in this class needs to pass two parameters, one is TextView, one is ProgressBar, and in Asynctask<integer, Integer, string> is the type of variable that you need to use, The first variable type is a parameter passed in by the Execute method in Mainactivity.java.

Then the Mainactivity.java code:

 Packagecom.example.test;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateTextView TextView; PrivateProgressBar ProgressBar; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView=(TextView) Findviewbyid (R.ID.TEXTVIEW1); ProgressBar=(ProgressBar) Findviewbyid (R.ID.PROGRESSBAR1); Progressbarasynctask Progressbarasynctask=NewProgressbarasynctask (TextView, ProgressBar); Progressbarasynctask.execute (1000); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (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 the parent activity in Androidmanifest.xml.        intID =Item.getitemid (); if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}
View Code

In the asynchronous task class, there is a Netoperatior class, which is used primarily for simulating download tasks, in which the current thread is allowed to rest for a second, noting that the thread is not executing in the UI thread, while the OnPreExecute () method and OnPostExecute () The method is executed in the UI thread, so you can interact with the interface here.

Netoperatior.java:

 Package com.example.test;  Public class Netoperatior {    publicvoid  operate () {        try  {            Thread.Sleep (+);         Catch (interruptedexception e) {            //  TODO auto-generated catch block             E.printstacktrace ();     }}}

Asynchronous tasks under Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.