Android Handlerthread analog Asynctask function (Threadtask)

Source: Internet
Author: User
Tags abstract final thread

Objective

Asynctask is a good thing to handle most application threads and update UI tasks because it uses a static thread pool internally, if you have a bunch of asynchronous tasks (such as global timing update data, Multiple asynctask in the same activity can be executed at the same time (for example, if a network request times out), it is bad, other tasks are still waiting, there will be a task card. At this point the need for direct thread, here reference Asynctask API encapsulated a threadtask, easy to code replacement when necessary, welcome to communicate!

Farmer Uncle: Http://over140.cnblogs.com

Import Android.os.Handler;
Import Android.os.HandlerThread;
Import Android.os.Looper;
    
Import Android.os.Message;
    Public abstract class Threadtask<params, Progress, result> {private Handlerthread mhandlerthread;
    Private Taskhandler Mhandler;
    Private Taskhandler Muihandler;
    
    Private params[] Mparams; Public Threadtask () {mhandlerthread = new Handlerthread ("Threadtask", Android.os.Process.THREAD_PRIORITY_BACKGROU
        ND);
        Mhandlerthread.start ();
        Mhandler = new Taskhandler (Mhandlerthread.getlooper ());
    Muihandler = new Taskhandler (Looper.getmainlooper ());
    
    } protected abstract result Doinbackground (Params ... Params); protected void OnPreExecute () {} protected void Onprogressupdate (Progress ... values) {} Protec Ted final void Publishprogress (Progress. Values) {muihandler.obtainmessage (message_progress, values). Sendtotarg
    ET (); } protected void OnpostexeCute (result result) {} public final Boolean iscancelled () {return mhandlerthread.isinterrupted ();
            Public final void Cancel (Boolean mayinterruptifrunning) {if (!mhandlerthread.isinterrupted ()) {
                try {mhandlerthread.quit ();
            Mhandlerthread.interrupt ();
            catch (SecurityException e) {e.printstacktrace ();
            catch (Exception e) {e.printstacktrace ();
    } oncancelled (); 
        } protected void Oncancelled () {} public void execute (Params ... Params) {mparams = Params;
        OnPreExecute ();
    Mhandler.sendemptymessage (Message_inbackground);
    private static final int message_inbackground = 0;
    private static final int message_postexecute = 1;
    
    private static final int message_progress = 2; Private class Taskhandler extends Handler {public TaskhAndler (Looper looper) {super (Looper);
            @SuppressWarnings ("unchecked") @Override public void Handlemessage (msg) { Switch (msg.what) {case MESSAGE_INBACKGROUND:mUiHandler.obtainMessage (message_postexecute
                , Doinbackground (Mparams)). Sendtotarget ();
            Break
                Case Message_postexecute:onpostexecute ((result) msg.obj);
            Break
                Case Message_progress:onprogressupdate ((progress[]) msg.obj);
            Break }
        }
    }
}

Code Description:

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/

Because OnPreExecute and OnPostExecute are both executing in the main thread and guaranteeing the order of execution, the handler is used to control the order of execution, depending on the loop, handler can switch between executing the code in the child thread or executing the code in the main thread.

End

In addition to not under the thread pool control, can also be the real cancel (Asynctask is not, just a mark), write some hasty, unavoidable bugs, welcome feedback!

Author: cnblogs Peasant Uncle

Related Article

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.