Android Useful Task Manager-tractor

Source: Internet
Author: User

In the normal Android development work, we often need to run time-consuming operation, sometimes for the user experience also need to display a waiting box, I was the previous practice is to open a thread, and then use the handler message to display and close the waiting box and related UI actions. Assuming that the task is much more, the frequent new thread makes the code seem confusing and not manageable, so I wrote tractor.

The basic functions of tractor are:
1. The code becomes neat. Don't use new thread and new Handler everywhere.
2. Be able to monitor the operation of the task, can cancel one or more tasks at any time;
3. The okhttp is encapsulated. Support large file upload, multi-threaded breakpoint download. Get,post and other network requests

Instructions for useClass diagram

The structure is actually very easy. Not many things.

Common tasks
//When the Loadlistenerimpl constructor is passed into the context, the ProgressDialog is displayedDonormaltask (NewLoadlistenerimpl ( This) {@Override           Public void OnStart(Object result) {Super. OnStart (Result); Setmessage ("task starts running"); }@Override           Public void onsuccess(Object result) {Super. onsuccess (Result);                 String response = (string) result; Setmessage ("End of task"); }@Override           Public void Onfail(Object result) {Super. Onfail (Result);                 String response = (string) result;          Setmessage (response); }@Override           Public void onloading(Object result) {Super. onloading (Result);//Do not write handler in the future, so you can handle the                intResponse = (int) result;Switch(response) { Case 1: Setmessage ("Running response="+ response); Break; Case 2: Setmessage ("Running response="+ response); Break; Case 3: Setmessage ("Running response="+ response); Break;default: Break; }                    }@Override           Public void OnCancel(Object result) {Super. OnCancel (Result); Setmessage ("The mission was canceled."); }@Override           Public void Oncancelclick() {Super. Oncancelclick (); Taskpool.getinstance (). Canceltask (mainactivity. This); }  }, This);

In the code block above, Loadlistenerimpl is the implementation class for Loadlistener, which listens to the entire process of task loading, with the advantage of using Loadlistenerimpl instead of Loadlistener two points:
1. Can not achieve all the methods, just according to their own needs to achieve the corresponding method can be;
ProgressDialog can be managed in 2.LoadListenerImpl. ProgressDialog can be self-contained in tractor, and can be customized.
Loadlistenerimpl part of the source code:

 Public  class Loadlistenerimpl implements Loadlistener {    PrivateWeakreference<context> Context;PrivateProgressDialog Mprogressdialog;PrivateString Mmessage ="Loading ...";Private LongMdismisstime = -;/** * does not show ProgressDialog * /     Public Loadlistenerimpl() {    }/** * Show ProgressDialog. The text displayed on it is the default * @param context * /     Public Loadlistenerimpl(Context context) {Init (context,NULL); }/** * Displays ProgressDialog, the text displayed on it is a message * @param Context * @param message * *     Public Loadlistenerimpl(Context context, String message)    {init (context, message); }/** * Set Custom ProgressDialog, assuming not set then use tractor * @param progressdialog */     Public void Setprogressdialog(ProgressDialog ProgressDialog)    {mprogressdialog = ProgressDialog; }    ......}

Of course, you can also achieve your own loadlistener. After all, it is interface-oriented programming.


Detailed implementation of the Donarmaltask method

 /** * Start a normal task * * @param Listener * @param Tag * *     Public void Donormaltask(Loadlistener Listener, Object tag) {taskpool.getinstance (). Execute (NewTask (tag, listener) {@Override             Public void OnRun() {Systemclock.sleep ( -); Notifyloading (1); Systemclock.sleep ( -); Notifyloading (2); Systemclock.sleep ( -); Notifyloading (3); Systemclock.sleep ( -); Random random =NewRandom ();//task is simulated, so randomly under                if(Random.nextboolean ()) {//notifysuccess (null);}Else{Notifyfail ("Bad, Mission failed."); }            }@Override             Public void Canceltask() {            }        }); }

The Taskpool.getinstance (). Execute () method finally puts the task to the line pool run. Taskpool is only responsible for joining and canceling tasks. The next task, described in the class diagram above, is that the task implements the Runnable interface and overrides run (), so the thread pool can run the task, and we'll look at how the run () method is implemented:

 Public Abstract  class Task implements Runnable {......@Override     Public Final void Run() {start ();        OnRun ();    Finish (); }     ......Private void Start() {Notifystart (NULL); ......    }/** * Implement this method to run a detailed task */     Public Abstract void OnRun();Private void Finish() {if(IsRunning ()) {//Default load SuccessMstatus = status.success; Notifysuccess (NULL);    } clear (); }

Run () runs Start (), OnRun () and finish (), and Notifystart (null) is called in the Start () method, and notifysuccess (null) is called in Finish (). This means that at the beginning of the UI thread, the task starts and the end of the UI thread is notified by default.

OnRun () is an abstract method that is implemented for task callers to run detailed tasks. The progress of the UI task can be notified through notifyloading (result) during the run. Notifysuccess (Result) and Notifyfail (Result) Notify the UI task of success and failure, and pass the required data result as a parameter to the UI thread.

As for the Canceltask () in the task, put it back when you cancel the task.

Timeout task
Dotimeouttask ( -,NewLoadlistenerimpl () {@Override                     Public void OnStart(Object result) {Super. OnStart (Result); Toast"Timeout task starts running"); }@Override                     Public void onsuccess(Object result) {Super. onsuccess (Result); Toast"Timeout task runs successfully"); }@Override                     Public void OnTimeOut(Object result) {Super. OnTimeOut (Result); Toast"Task timed out"); }                }, This); ....... Public void Dotimeouttask(LongTimeout, Loadlistener Listener, Object tag) {taskpool.getinstance (). Execute (NewTask (timeout, tag, listener) {@Override             Public void OnRun() {Systemclock.sleep ( +); }@Override             Public void Canceltask() {            }        }); }

Can see. A timeout task is simply a timeout parameter for a task constructor compared to a normal job. The meaning of this timeout parameter is the time limit for the task to run. If this limit is exceeded, the OnTimeOut () method is recalled.

Cancel a task

In the normal development process, sometimes an ultra-time-consuming operation, the time-consuming operation is not returned when the page is closed. When the page is closed after the time-consuming operation to return, when the need to manipulate the control can be reported null or some other exception, in order to avoid the exception, we usually need to make some page is active state inference, but this is always very troublesome. Tractor overcomes this problem and is able to invoke the method of canceling the task, like this:

//取消任务的方法,參数能够是任务的tag,也能够是task。假设是tag,则取消tag相关的全部任务。是task则取消指定的task。//能够在onDestroy()中调用TaskPool.getInstance().cancelTask(tag|task);

This call will then call Notifycancel (NULL) and display the effect on the UI that the user's task has been canceled, tractor has a feature: when the task has results (canceled, timed out, succeeded and failed), perhaps Notifyxxx () will not be notified to the UI thread, So assuming that the task is running the cancel task code, when the task has the result returned. UI callbacks will not be run. Then the problem mentioned above also does not exist, on the province's own to add inferences.


As mentioned earlier, the code that cancels the task can only have a cancellation effect on the UI, but the task is actually running. Although the user can not see but the resources are still in the loss, so not yet.
From the class diagram you can see that the task has OnRun () and Canceltask () two abstract methods, OnRun () is running detailed tasks, and Canceltask () is the operation that runs a detailed cancel task. He is running in a non-UI thread. It is up to you to decide how to stop the task in detail.

Network Request Section

To make the task Manager look more practical. I encapsulated the network framework, the implementation is okhttp, can support head,get,post, multi-threaded download, large file upload and some other HTTP requests. Because it is interface-oriented programming, it is assumed that there will be more suitable libraries in the future, so it is very convenient to replace Okhttp. This part of the sample I do not post out, interested to see the code, very easy, the code is all in the Mainactivity of the demo module.


Download:

Upload files:

finally

Suppose you have any questions and suggestions to leave a message or send me an e-mail. Tractor is hosted on GitHub, click here to get the source code. Welcome to star or follow!

Android Useful Task Manager-tractor

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.