Because the project needs to encapsulate its network layer, mainly to improve its original schema, the use of callbacks to the network access and return the results of processing, there is a layer between the view layer and the network layers to allocate a variety of network requests, so that can be easily scheduled and managed.
I will not take the original project code to demonstrate, I wrote a demo, the first is the bottom, processing the most basic HTTP protocol, which contains an Execute method, used for post or get data, here for convenience I wrote only a GET, Can be changed to post or other methods according to the specific needs:
You can see that the arguments to the Execute method are the String URL and the map<string,string> map, so we need a pojo to construct the parameters:
Next is a factory class, where simple Factory mode is used, which can be easily created according to the different parameters of the Pojo example:
Next is the middle tier, all the network methods need to go through here to invoke the underlying protocol, where the various network methods of scheduling and management:
Defining the callback interface yourself is generally done with success processing and error handling, and can be further abstracted:
Finally, it is called in the main function, which calls the method running in the sub-thread, only needs to construct the callback callback function, simple
Calls can:
Final Networkpojo request = Networkfactory.creategao ();//Construction 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, the view layer and the bottom of the middle of an extra layer, to provide a variety of calls running on different threads, the use of its callback method to implement it, the biggest is to facilitate scheduling and management.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Encapsulation of the Android network layer