Asynctask use of asynchronous threads

Source: Internet
Author: User

Use asynchronous tasks to load bitmap and emulate ProgressBar progress bar cases

 Public classMainactivityextendsappcompatactivity { Publiccontext Context; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {Intent Intent=NewIntent (); Intent.setclass (mainactivity. This, Imagetext.class);            StartActivity (Intent);        }        }); Button button1=(Button) Findviewbyid (R.id.button2); Button1.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {Intent Intent=NewIntent (); Intent.setclass (mainactivity. This, Progressbartest.class);            StartActivity (Intent);    }        }); }}

Set the listener event to call two different activity, the first to load the network pictures of the activity needs to use the network, in Mainfest to set the user access to the network permissions

In setting up listener events, using the intent calling code, using the 6.0 API, you need to set the parameter in intent to (Xxxx.this,xxxxx.class) to resolve an invalid pointer problem.

Code to load a network picture

 Public classImagetextextendsappcompatactivity {PrivateImageView ImageView; PrivateProgressBar ProgressBar; Private StaticString url= "Http://img.my.csdn.net/uploads/201504/12/1428806103_9476.png"; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.imagetest); ImageView=(ImageView) Findviewbyid (R.ID.IMAGE11); ProgressBar=(ProgressBar) Findviewbyid (R.id.bar); Newmyasynctask (). Execute (URL); }    classMyasynctaskextendsAsynctask<string,void,bitmap>{@Overrideprotected voidOnPostExecute (Bitmap Bitmap) {//ProgressBar is set to invisible after a picture has been loadedprogressbar.setvisibility (View.gone); //set up an incoming network picture bitmapImageview.setimagebitmap (bitmap); Super. OnPostExecute (bitmap); } @Overrideprotected voidOnPreExecute () {//Show progress barprogressbar.setvisibility (view.visible); Super. OnPreExecute (); } @OverrideprotectedBitmap doinbackground (String ... strings) {//gets the value of the passed-in string from the ExcuteString url=strings[0]; //bitmap must be initializedBitmap Bitmap =NULL; //set up objects for network connectionsURLConnection Connection; //setting the input streamInputStream InputStream; Try {                //To obtain a network connection object, you must import the Java.net.URL packageconnection=Newurl (url). OpenConnection (); InputStream=Connection.getinputstream (); Thread.Sleep (3000); //encapsulating the input streamBufferedinputstream bis=NewBufferedinputstream (InputStream); //parsing the input streambitmap=Bitmapfactory.decodestream (bis); //closing the input stream and encapsulating the streamInputstream.close ();            Bis.close (); } Catch(IOException |interruptedexception e)            {E.printstacktrace (); }            //returns the bitmap that have been received            returnbitmap; }    }    }

Write the idea of code to comb:

manipulating the UI with the Onproexcute method and the Onpostexcute method to set the image
mprogressbar.setvisbility (view.visible) Show progress bar
Onpostexcute (BitMap BitMap)//bitmap a doingbackground returned by the BitMap method
in the main method, call Myasyctask's Execute method incoming (URL)
by invoking the Execute method with an instance of Asynctask, you can turn on the asynchronous operation of Asynctask and pass in one or more parameters in the Execute method as a parameter passed in our Doingbackground method.
The Initialize method is called in the OnPreExecute method of Asynctask, which initiates an asynchronous operation in the background prompting the user to wait,

Call the real Doingbackground method to start the real asynchronous processing, where the entire method is now in the sub-thread, all the time-consuming operations in this method, and return the value to be returned to the type of the value we set

Getting the results we returned in the OnPostExecute method, the Onpostexcute method also runs in the main thread so that we can manipulate the UI, which is the entire process that Asynctask calls.


Open the network permissions you want to access in the Mainfest
Add button Call

********************************************************************

Set the code for ProgressBar

 Public classProgressbartestextendsappcompatactivity {PrivateMaysnctask Mtask; PrivateProgressBar ProgressBar; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.progressbartest); //methods for getting the asynctask of a custom inner classmtask=NewMaysnctask (); //Run this methodMtask.execute (); ProgressBar=(ProgressBar) Findviewbyid (R.id.progressbar); } @Override//If you want to save the user important data before the activity exits, it must be handled in OnPause, because when the system is in urgent need of memory, OnStop and OnDestroy will not be executed.    protected voidOnPause () {Super. OnPause (); if(mtask!=NULL&&mtask.getstatus () = =AsyncTask.Status.RUNNING) {Mtask.cancel (true); }    }    classMaysnctaskextendsAsynctask<void,integer,void>{@Overrideprotected voidonprogressupdate (Integer ... values) {Super. Onprogressupdate (values); //to get the value passed in from Doingbackground, for the first value of the incoming shaping array values, use the Setprogress method to set the ProgressBar methodProgressbar.setprogress (values[0]); if(iscancelled ()) {//determines whether the Asynctask is a cancel state if the cancel state is return. The return statement returns the value of the function to the keynote function                return; }} @Overrideprotectedvoid Doinbackground (void ... voids) { for(inti=0;i<100;i++){                if(iscancelled ()) { Break; }                //publishprogress () update progress, pass the progress parameter publishprogress to Onprogressupdate () as an integerpublishprogress (i); Try {                    //set the effect of a delay of 300 millisecondsThread.Sleep (300); } Catch(interruptedexception e) {e.printstacktrace (); }            }            return NULL; }    }    }

There is no way to stop the previous thread's workaround in code that runs the motion of the simulated progress:

Asynctask By default, it waits for the previous thread to execute before executing the next thread, and to cancel the mechanism, you can keep the asynctask and activity life cycle consistent
protected void OnPause () {
super.onpause ();
if (mtask! = null && mtask.getstatus () = = AsyncTask.Status.RUNNING) {
//Just sends a cancel request, marks the Asynctask as cancel, but does not actually cancel the execution of the thread
//Actually the Java Voice has no way to rudely stop a running thread directly
Mtask.cancel (true);
}
}

Therefore, the Doinbackground method and the Onprogressupdate method should be added to the iscancelled () method to judge, marked as cancel, then jump out of the loop, as soon as possible to end the remaining operation of the current thread, start the next thread

Asynctask Implementation of the mechanism: the bottom line through the role of pool, when we do not complete a thread, the subsequent thread is unable to execute;
Call the Cancel method to cancel a asynctask thread, and do not stop the thread directly, just send a cancel request to the Asynctask and identify it as the cancel state;
in Java, it is not possible to rudely stop a thread directly, we must wait for a thread to complete before we can do the following. (Must be judged by the status value to jump out of the sub-thread loop operation)

only Doinbackground is executed in a non-UI thread
mytask!=null&&mytask.getstatus () = = AsyncTask.Status.RUNNING
Ansystask cannot be canceled immediately even if Cancel is set to True, just set the status to cancel
so when Doinbackground and Onupdatexx detect iscancled () is not true

Asynctask use of asynchronous threads

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.