Android Network Layer encapsulation and android Encapsulation
Because the project needs to encapsulate its network layer, it mainly improves its original mode and uses the callback method to process network access and return results, in addition, an intermediate layer is added between the View layer and the network layer to allocate various network requests, which facilitates scheduling and management.
I did not use the code of the original project for demonstration. I wrote a demo. The first is the bottom layer, which processes the most basic Http protocol and contains an execute method, for Post or Get to Get data, I wrote only one Get here for convenience. You can change it to Post or another method as needed:
We can see that the parameters of the execute method are String url and Map <String, String> map, so we need a POJO to construct these parameters:
Next is a factory class. Here we use the simple factory mode, which can easily create POJO instances based on different parameters:
The next step is the middle layer. All network methods must pass through this to call the underlying protocol, where scheduling and management of various network methods are performed:
Custom callback interfaces are generally used for Success processing and Error processing, which can be further abstracted:
Finally, it is called in the main function. Here we call the method running in the sub-thread. We only need to construct the Callback function, which is simple.
Call:
Final NetworkPOJO request = NetworkFactory. creategao (); // construct POJObtn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {Network. postOnThread (request, new Callback () {@ Overridepublic void onSuccess (String json) {text. setText (json) ;}@ Overridepublic void onError () {text. setText ("Error ");}});}});
In this way, an intermediate layer is added between the View layer and the underlying layer, and various calling methods run in different threads are provided. You can implement the callback method when using the method, the biggest difference is convenient scheduling and management.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.