Pre-network Android Pre-load network framework

Source: Internet
Author: User

Network optimization is a very important part of all app development, and if the network request is preceded by a click to jump activity, the speed of the network load will be improved. That is, the network pre-load box frame.

Network pre-load frame, monitor network pre-load frame-network preload, networking preload the framework.-pre-network

Framework Description

Pre-network: It is a pre-loading frame based on the observer pattern, which can optimize the load speed of the network; Each network request corresponds to the observer, as long as the subscribed observer can get the instance of the Observer.

Basic Use Method

Add Dependencies:

implementation ‘com.liyihang:pre-network:1.2.2‘

Each observer network must have a string unique ID to identify him, and the observer subscription is also identified by a unique ID that is then subscribed to by the Observer.
Here for example one the observer requested of I is web_data;

First, the Observer network request is created;
The code is as follows:

PreNetworkHelper.getInstance()                    .removeRequestObservable("web_data") // 首先清楚之前的相同id的被观察者请求移除,如果不移除相同id请求没有办法添加进入。                    .addRequestObservable(new PNQuickRequest("web_data", "http://baidu.com/"));// 添加被观察者,添加后立即执行网络请求。

Pnquickrequest is a simple encapsulation of the observer; You can look at the code:

Package Com.prenetwork.liyihang.lib_pre_network;import java.util.map;/** * Created is Liyihang on 18-1-16.    */public class Pnquickrequest extends Pnrequestobservable {private String ID;    Private String URL;    Private String parms;    Private map<string, string> header;        Public pnquickrequest (string id, string url) {this.id = ID;        This.url = URL;        Parms=null;    Header=null;        } public pnquickrequest (string id, string URL, string parms) {this.id = ID;        This.url = URL;        This.parms = parms;    Header=null;        } public pnquickrequest (string id, string URL, string parms, Map<string, string> header) {this.id = ID;        This.url = URL;        This.parms = parms;    This.header = header;    } @Override Public String getId () {return id;    } @Override public map<string, string> Getrequestheader () {return header;        } @Override Public String getrequestparms () {return parms;    } @Override Public String Getrequesturl () {return URL; }}

Where ID is the unique ID, URL network request address, Parm network request parameter, header network request request headers field.

How to subscribe to the request code is as follows:

PreNetworkHelper.getInstance().addObserver(new PNObserver() {            @Override            public void call(PNRequestObservable observable) {                final String result = observable.getResult();// 获取网络请求内容 , 这里发生在非ui线程中。observable就是被观察者实例                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        //... do samething                    }                });            }            @Override            public String getId() {                return "web_data";// 唯一id            }        
In-depth use

Basically the company development app will encapsulate its own network request framework, Pre-network Use network request is the base httpurlconnection:

        executor.submit(new Runnable() {            @Override            public void run() {                if ("GET".equals(getRequestMethod()))                    result = PNGetPostUtil.sendGet(getRequestUrl(), getRequestParms(), getRequestHeader());                if ("POST".equals(getRequestMethod()))                    result = PNGetPostUtil.sendPost(getRequestUrl(), getRequestParms(), getRequestHeader());                dataChange();            }        });

So it is to use their own company network request, first to create a implementation of the Pnrequestobservable class of the request body, where an inheritance okhttp as an example:

/** * Created by Liyihang on 18-1-17. */public class Myrequestobservable extends Pnrequestobservable {private static final okhttpclient http_client=new Okht    Tpclient (); @Override public String getId () {return ' request_id ';//Unique ID} @Override public map<string, string& Gt    Getrequestheader () {return null;    } @Override Public String getrequestparms () {return null;    } @Override Public String Getrequesturl () {return null; } @Override public void Handlerrequest () {//Super.handlerrequest (); Closes the original network request processing method Request.builder Bui        Lder=new Request.builder ();        Builder.url ("https://www.baidu.com/"); Http_client.newcall (Builder.build ()). Enqueue (New Callback () {@Override public void onfailure (reques            T request, IOException E) {//The network must be called requestpost (NULL) after completion; } @Override public void Onresponse (Response Response) throws IOException {String data = Response.body (). String ();            Do samething ...//the network must call Requestpost (data) after completion;    }        }); }}

Calling methods such as:

        PreNetworkHelper.getInstance()                .removeAllObservable()// 删除所有请求                .addRequestObservable(new MyRequestObservable())// 添加请求和执行                .addObserver(new PNObserver() { //添加回调                    @Override                    public void call(PNRequestObservable observable) {                        MyRequestObservable result= (MyRequestObservable) observable;                        PNUtils.msg("end:"+result.getResult());                    }                    @Override                    public String getId() {                        return "request_id";                    }                })                .removeAllObservable();

One voyage

Pre-network Android Pre-load network framework

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.