Simple application of bolts frame in wirelessly

Source: Internet
Author: User

In the new company's project, is the bolts framework to build the network request, because previously did not contact the framework, so can only look at the beginning (in fact, I prefer to use Rxjava+retrofit to build Apps request layer, But,whatever ... ), many of the following are in the online reading of the data after their own demo to verify the obtained, part of the translation of GitHub's bolts framework of the documentation, but also some of my own on-line tutorial on the basis of their own verification after the code, if there is a similar, purely coincidental.


1. Introduction

Bolts is a lightweight library of functions for simplifying mobile app development, written by parse and Facebook for internal use, and later decided to open source for use by a broad set of developers. Tasks, making complex asynchronous code structures easy to manage. The role of "Task" in Android and iOS is like JavaScript's promise.

2. Download

Download the jar package from here or compile it in Gradle.

dependencies {  compile ' com.parse.bolts:bolts-tasks:1.4.0 '  compile ' com.parse.bolts:bolts-applinks:1.4.0 ' }

3 , Tasks

    to build a fast-respondingAndroidapplication, you cannotUIrun any time-consuming action in the thread, and be careful to avoid blockingUIthread, which means you need to perform various operations in the background. To make this process easier, we added a class called "Task". ATaskrepresents an asynchronous operation. TaskThe result returned by the operation to continue processing is returned by an asynchronous operation. When aTaskreturned by the function, it has begun to complete its task. Taskdoes not bind to a particular threading model: it represents an operation being completed, not an operation being executed. Taskwith other asynchronous methods, such asAsynctask) compared to a number of advantages.

(1) Task consumes less system resources because the task does not occupy threads while waiting for other tasks

(2) When performing a series of tasks, you do not need to write pyramid-like nesting code as you would when using callback.

(3) Tasks can be combined, allowing you to perform branching, parallel, and compound error handling without the need for nested code and various complex named callback.

(4) You can organize your task-based code and execute them in an orderly manner instead of scattering your logic into messy callback functions.


4. Call

We know that the core of bolts is asynchronous, so like Rxjava, we can decide whether our code should run on the UI thread, the current thread, or the background thread, so there are several thread pools defined in the task class. It is convenient for us to use this framework as a parameter in the implementation of calling our code in different threads, which are the following thread pool code:

/**    * An {@link java.util.concurrent.Executor} This executes tasks in parallel.    *  /public static final Executorservice background_executor = Boltsexecutors.background ();  /**   * An {@link java.util.concurrent.Executor}, executes tasks in the current thread unless   * The stack runs t Oo deep, at which point it would delegate to {@link task#background_executor} on   * order to trim the stack.   *  /private static final Executor Immediate_executor = Boltsexecutors.immediate ();  /**   * An {@link java.util.concurrent.Executor}, executes tasks on the UI thread.   *  /public static final Executor ui_thread_executor = Androidexecutors.uithread ();

Background_executor is running in a background thread.

Immediate_executor as I understand it is running on the current thread (I'm not sure, because it's useless so there's no testing, but it should be correct)

Ui_thread_executor is running on the UI thread (that is, the main thread)


Knowing the differences between these threads, we can start using bolts to run our code, and the Getimagefromweb () method in the following code is a way to download a picture from the Web and save it in the global variable bitmap, which is ignored.

(1) Run a single task


Task.call (New callable<bitmap> () {        @Override public        Bitmap call () throws Exception {//Here you can return a null value, To set the return type to void, return other types of usage will be mentioned below            //The code you want to execute    Bitmap Bitmap = Getimagefromweb ();            return <span style= "font-family:arial, Helvetica, Sans-serif;" >bitmap</span><span style= "font-family:arial, Helvetica, Sans-serif;" >;    The bitmap returned here will be in the result of the task execution described below </span>        }    }, Task.background_executor);//The parameters here can be referenced to fill in the other thread pool, Control which thread this code runs on

(2)"ContinueWith" Method

Each task has a method called ContinueWith and it comes with a parameter continuation. Continuation is the interface you need to implement, and the way you need to implement it. The then method is called after the task completes, and you can use this method to check whether the task succeeds and to obtain its results.

Task.call (New callable<bitmap> () {@Override public Bitmap call () throws Exception {//Here you can return a null value                , set the return type to void, and return other types of usage will be mentioned below//the code you want to execute Bitmap Bitmap = Getimagefromweb ();    return bitmap; The bitmap returned here will be processed in the task execution results described below}}, Task.background_executor)//run in a background thread. ContinueWith (New Continuation<bitmap, void> () {@Override public Void then (Task<bitmap> t                        Ask) throws Exception {//Set UI if (Task.isfaulted ()) {                                                                                             Exception exc = Task.geterror ();//Picture loading failed, error handling } else if (task.iscompleted ()) {//Picture loaded successfully set        Image (Task.getresult ());//task.getresult () is the method that gets the result after the successful execution of the task} return null;             }}, Task.ui_thread_executor);//run in the UI thread 
(3) If we only need to care about the success of the last task to be processed, then we can use the. Onsuccess method instead of the. ContinueWith method, as follows:

Task.call (New callable<bitmap> () {            @Override public            Bitmap call () throws Exception {//need to return a Bitmap                The code you want to execute                Bitmap Bitmap = Getimagefromweb ();                return bitmap;    The bitmap returned here will be in the task execution results described below            }        }, Task.background_executor)//Background thread run                . onsuccess (New continuation< Bitmap, object> () {                    @Override public                    Void then (task<bitmap> Task) throws Exception {                            //Picture loaded successfully C14/>setimage (Task.getresult ());//Display the picture to                        return null;                    }                }, Task.ui_thread_executor);//main thread run

(4)After we know how to use the above two methods, we can use them to perform a sequential task, the following sample code needs to perform three tasks, after the execution of task 1 succeeds, the task 2 will be executed, and task 2 will be processed in task 3 regardless of the success of the failure.


Task.call (New callable<bitmap> () {@Override public Bitmap call () throws Exception {                You want to execute the code, Task 1 Bitmap Bitmap = Getimagefromweb ();    return bitmap; The bitmap returned here will be in the task execution results described below}}, Task.background_executor)//Background thread run. onsuccess (New Continu Ation<bitmap, bitmap> () {@Override public Bitmap then (task<bitmap> Task                        ) throws Exception {//do something, Task 2 Bitmap b = Task.getresult ();                    return b;  }}, Task.background_executor)//Background thread runs. ContinueWith (New Continuation<bitmap, void> ()                        {@Override public Void then (task<bitmap> Task) throws Exception {       Task 3 if (task.isfaulted ()) {//Picture loading failed, error handling                 } else if (task.iscompleted ()) {//Picture loaded successfully setimage (                        Task.getresult ());                    } return null; }}, Task.ui_thread_executor);//main thread run

(5)In addition to performing tasks sequentially, we can also perform tasks in parallel, in the following code, Task 1 creates Task 2 and task 3 for parallel execution, and invokes task 4 for result processing when both tasks are executed.

Task.call (New callable<list<task<bitmap>>> () {@Override public list<task<bi Tmap>> call () throws Exception {list<task<bitmap>> tasks = new ARRAYLIST&LT;TASK&LT;BITM                Ap>> ();  Task<bitmap> Task1 = Task.call (new callable<bitmap> () {@Override public                    Bitmap call () throws Exception {//Task 2 return Getimagefromweb ();                }}, Task.background_executor);  task<bitmap> Task2 = Task.call (new callable<bitmap> () {@Override public                    Bitmap call () throws Exception {//Task 3 return Getimagefromweb ();                }}, Task.background_executor);                Tasks.add (TASK1);                Tasks.add (TASK2); Task.whenall (tasks). WaitforcoMpletion ();    return to tasks; return here}}, Task.background_executor)//Background thread run. ContinueWith (New continuation<list< Task<bitmap>&gt, void> () {@Override public Void then (task<list<task  <Bitmap>>> Task) throws Exception {//Task 4 if (task.isfaulted ())                        {//error handling Exception Exception = Task.geterror (); } else if (task.iscompleted ()) {//takes out two side-by-side tasks, gets the return value of the execution end F                                    or (task<bitmap> T:task.getresult ()) {if (t.iscompleted ()) {                                Task Execution Success SetImage (T.getresult ());                    }}} return null;   }             }, Task.ui_thread_executor);//main thread run 

(6)The task can also be deferred before executing ContinueWith, just call. Delay (time) before calling ContinueWith.








Simple application of bolts frame in wirelessly

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.