Talking about asynchronous loading in Android "canceling asynchronous loading" two

Source: Internet
Author: User

First of all, I have to explain why my title cancels the asynchronous loading of quotation marks, because it is possible that the final implementation effect is not what you imagined. Everybody look at canceling asynchronous loading, isn't that easy? Is there a cancel method in Asynctask? Is it OK to call the method directly? But is this actually the case? If that's the case, I'm sure I didn't have to write about it as a blog post. Why is there such an idea? It actually stems from a bug in my previous demo, then resolves the bug and needs to cancel the async task, so let's take a look at it.

First of all, let's review the previous blog to load the progress bar demo.

Asynctask sub-class:

01.package com.mikyou.utils;  03.import Android.os.AsyncTask;  04.import Android.widget.ProgressBar;  05.import Android.widget.TextView;    .07.public class Mikyouasynctaskprogressbarutils extends Asynctask<void, Integer, string>{08.  Private TextView TV;  ProgressBar private Bar; Public mikyouasynctaskprogressbarutils (TextView Tv,progressbar bar) {//Here I use the constructor to pass Textview,progressbar directly,        The UI 11 is then updated directly in the class.  This.bar=bar;  THIS.TV=TV;    13.14.    } 15.    @Override 16.        Protected String doinbackground (Void ... params) {17.            for (int i=1;i<101;i++) {18.                try {19.  Thread.Sleep (1000);                The.} catch (Interruptedexception e) {21.  E.printstacktrace ();            22.} 23.  Publishprogress (i);        24.} 25.  Return "Download Complete";    26.} 27.    @Override 28.        protected void Onprogressupdate (Integer ... values) {29.  Bar.setprogress (Values[0]);      30.  Tv.settext ("Download Progress:" +values[0]+ "%");  Super.onprogressupdate (values);    32.} 33.    @Override 34.        protected void OnPostExecute (String result) {35.  Tv.settext (result);  Super.onpostexecute (result);   37.} 38.}

Mainactivity

01.package Com.mikyou.asynctask;  03.import com.mikyou.utils.MikyouAsyncTaskProgressBarUtils;  05.import android.app.Activity;  06.import Android.os.Bundle;  07.import Android.view.View;  08.import Android.widget.Button;  09.import Android.widget.ProgressBar;  10.import Android.widget.TextView;    One. 12.public class Mainactivity extends Activity {13.  Private Button downLoad;  Private ProgressBar Bar;  . private TextView TV;    17. @Override.        protected void OnCreate (Bundle savedinstancestate) {18.  Super.oncreate (savedinstancestate);  Setcontentview (R.layout.activity_main);  Initview ();    21.} 22.        private void Initview () {23.  Bar= (ProgressBar) Findviewbyid (R.id.bar);  tv= (TextView) Findviewbyid (r.id.tv);    25.} 26.        public void Download (view view) {27.  Mikyouasynctaskprogressbarutils mikyouasynctaskprogressbarutils=new mikyouasynctaskprogressbarutils (TV, bar); Mikyouasyn.Ctaskprogressbarutils.execute ();  29.} 30.   31.}

Run the result of the demo bug:



By analyzing the demo above, you will find:

When we click to start the download, the progress bar starts to update, then in the update midway out of activity, and then again into the activity, click Start Download will find, wait for a while, the progress bar to start updating.

Reason: This is not a bug in this program, but a mechanism for asynchronous loading, because asynchronous loading from the source code, we can conclude that its underlying implementation or thread or Thread-pool+handler mechanism

The mechanism is that if the currently started thread is not finished, the other threads must wait, which explains why asynchronous loading is secure because it avoids the security problems that thread synchronization can bring.
Workaround: In fact, it is very simple to bind the life cycle of an asynchronous load to the life cycle of our activity, and when I quit the activity for the first time in the middle of a break, I call OnPause
method, simply cancel the interrupted asynchronous task in the OnPause method and cancel the thread in the current thread pool, and when the next re-entry, the thread pool is not
Other sub-threads, then it does not have to wait for other threads to run directly.

From the above analysis, we can get a solution, that is, how to cancel the current asynchronous task, then we use the Cancel method to terminate the asynchronous task according to everyone's unanimous idea.

Come to see if we can achieve the effect we want?? Look at it together.

Package Com.mikyou.asynctask;import Com.mikyou.utils.mikyouasynctaskprogressbarutils;import android.app.Activity; Import Android.os.asynctask;import android.os.bundle;import Android.view.view;import Android.widget.Button;import Android.widget.progressbar;import Android.widget.textview;public class Mainactivity extends Activity {private Button Download;private ProgressBar bar;private TextView tv;private mikyouasynctaskprogressbarutils mtask;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Initview ();} private void Initview () {bar= (ProgressBar) Findviewbyid (R.id.bar); tv= (TextView) Findviewbyid (r.id.tv);} public void Download (view view) {Mtask=new mikyouasynctaskprogressbarutils (TV, bar); Mtask.execute ();} Binds the life cycle of an asynchronous task to activity @overrideprotected void OnPause () {//Determines whether the current asynchronous task is empty and determines whether the state of the current asynchronous task is a running state {RUNNING (run). PENDING (Preparation), finished (finish)}if (Mtask!=null&&mtask.getstatus () ==asynctask.status.runNING) {/** *cancel (true) cancels the current asynchronous task, passing in true, indicating that the operation of the thread that is already running when the asynchronous task is interrupted, * but generally for thread security to let it continue set to True * */mtask.cancel (TRUE);} Super.onpause ();}}
Operation Result:

We looked closely and found that it seemed that the Cancel method we added was useless, which is what I need to talk about.

Why can't I stop an asynchronous task, which is why?

Note: This is because the Cancel method simply emits a signal to cancel the asynchronous task, marking the current asynchronous task as the cancel state instead of actually canceling the execution of the thread, while the thread in the asynchronous task is still executing and not ending, so the effect is still the same. And in Java, we can't just force a thread to stop it. Since we know we can't cancel a thread that's already running, how do we fix this bug? In the asynchronous task give us a iscanceled callback method, that is, when I have given the current asynchronous, called the Cancel (true) method, issued a request to cancel the asynchronous task signal, then the iscanceled callback method will directly return a true , then we can terminate the operation in the thread instead of terminating the thread by judging whether the current asynchronous task iscanceled is true, so that the interface appears as if the operation in the thread is terminated, and the thread is actually still running

Because we're not going to kill a thread outright using brute force, we can't just cancel an asynchronous task, but we can send a request signal to cancel the asynchronous task by calling the Cancel method, which sets the value of mcanceled to true. Marked as the asynchronous task was canceled, the callback method iscanceled to return a true, indicating that the asynchronous task was canceled. If you have any questions, let's look at the source code of the cancel counter method.

    /** * <p>attempts to cancel execution of this task. This attempt would * fail if the task has already completed, already been cancelled, * or could not being cancelled fo R some other reason. If successful, * and this task have not started when <tt>cancel</tt> was called, * this task should Neve R run. If The task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whet Her the thread executing this task should is interrupted in * a attempt to stop the task.</p> * * < P>calling This method would result in {@link #onCancelled (Object)} being * invoked on the UI thread after {@link #do Inbackground (object[])} * returns. Calling this method guarantees the {@link #onPostExecute (Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link #isCancelled ()} periodically from * {@ Link #doInBackground (object[])} to finish THe task as early as * possible.</p> * * @param mayinterruptifrunning <tt>true</tt> if the th Read executing this * task should is interrupted;     Otherwise, in-progress tasks is allowed * to complete. * * @return <tt>false</tt> If the task could not being cancelled, * typically because it has alre     Ady completed normally; * <tt>true</tt> otherwise * * @see #isCancelled () * @see #onCancelled (Object) */PU        Blic Final Boolean cancel (Boolean mayinterruptifrunning) {Mcancelled.set (true);    Return Mfuture.cancel (mayinterruptifrunning); }

The mcanceled will be set to true, and the value will be passed through the Iscanceled method callback. So, we use the idea that since we can't terminate a thread, we can solve the bug indirectly.

Instead of terminating the thread, the operation in the thread is terminated directly by judging the value.

Package Com.mikyou.asynctask;import Com.mikyou.utils.mikyouasynctaskprogressbarutils;import android.app.Activity; Import Android.os.asynctask;import android.os.bundle;import Android.view.view;import Android.widget.Button;import Android.widget.progressbar;import Android.widget.textview;public class Mainactivity extends Activity {private Button Download;private ProgressBar bar;private TextView tv;private mikyouasynctaskprogressbarutils mtask;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Initview ();} private void Initview () {bar= (ProgressBar) Findviewbyid (R.id.bar); tv= (TextView) Findviewbyid (r.id.tv);} public void Download (view view) {Mtask=new mikyouasynctaskprogressbarutils (TV, bar); Mtask.execute ();} Binds the life cycle of an asynchronous task to activity @overrideprotected void OnPause () {//Determines whether the current asynchronous task is empty and determines whether the state of the current asynchronous task is a running state {RUNNING (run). PENDING (Preparation), finished (finish)}if (Mtask!=null&&mtask.getstatus () ==asynctask.status.runNING) {/** *cancel (true) cancels the current asynchronous task, passing in true, indicating that the operation of the thread that is already running when the asynchronous task is interrupted, * but generally for thread security to let it continue set to True * */mtask.cancel (TRUE);/* * * But after re-running you will find that the effect is still not effective, * Note: This is because the Cancel method simply emits a signal to cancel the asynchronous task, marking the corresponding current asynchronous task as the cancel state instead of actually canceling the execution of the thread, * The threads in the async task are still executing and not ending * so the effect is still the same, and in Java we can't directly force a thread to stop * since we know we can't cancel a thread that's already running, but how do we fix it? * Give us a iscanceled callback method in the asynchronous task, that is, when I have called the Cancel (true) method to the current asynchronous task *, issued a request to cancel the asynchronous task signal, then the iscanceled callback method at this time * Will directly return a true, then we can terminate the operation in the thread by judging whether the current asynchronous task iscanceled is true, instead of terminating the thread, so that the interface appears as if the operation in the thread is terminated, but actually the thread is still running * */} Super.onpause ();}}

Subclass of Asynctask

Package Com.mikyou.utils;import Android.os.asynctask;import Android.widget.progressbar;import Android.widget.textview;public class Mikyouasynctaskprogressbarutils extends Asynctask<void, Integer, String>{ Private TextView tv;private ProgressBar bar;public mikyouasynctaskprogressbarutils (TextView tv,progressbar bar) {// Here I use the constructor to pass the Textview,progressbar directly, and then update the UITHIS.BAR=BAR;THIS.TV=TV directly in the class;} @Overrideprotected String doinbackground (Void ... params) {for (int i=1;i<101;i++) {try {if (iscancelled ()) {// If True then indicates that a signal has been requested to cancel the current task, since the running of the thread could not be terminated, but could terminate a series of operations in the threads break;} Thread.Sleep (100);} catch (Interruptedexception e) {e.printstacktrace ();} Publishprogress (i);} Return "Download Complete";} @Overrideprotected void Onprogressupdate (Integer ... values) {if (iscancelled ()) {///judgment if True then indicates that a signal has been requested to cancel the current task, Since it is not possible to terminate the running of a thread, it can terminate a series of operations in the threads so that it runs empty and does not achieve the effect of updating the UI return; Bar.setprogress (Values[0]); Tv.settext ("Download Progress:" +values[0]+ "%"); Super.onprogressupdate (values);} @Overrideprotected void OnPostExecute (String result) {tv.seTtext (result); Super.onpostexecute (result);}} 

Operation Result:


Talking about asynchronous loading in Android "canceling asynchronous loading" two

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.