Talking about the Android client project framework, talking about the android Client

Source: Internet
Author: User
Tags hp server

Talking about the Android client project framework, talking about the android Client

I have been writing Android for some time, working, learning, and accumulating. Only when I encounter problems and spend time researching can I improve my abilities. If I don't need a tool, it will rust slowly! Some adjustments were made to the company's Project Server framework last month. However, at that time, my project was not transplanted with the framework, and I was still the code of my predecessors. I was so exhausted that I was almost killed, I worked overtime for two days each weekend, and the quality of the results was very poor. After the change was completed, I decided to take the time to transplant my framework, my framework has been developed by myself. I would like to share it with you. If something is wrong, please criticize and correct it. Thank you!

First of all, to build a client framework, we need to consider all the things the client wants to do:

1. encapsulate business data for sending requests to the server

2. Connect to the server and send network requests

3. Get the response result, parse the data, return to your own interface for logical judgment, and control the interface display

4. Control your own interface Display Based on Data

The above four points are the things that the client needs to do. We will not talk about the fourth point, as long as we get the data and interface control, we can implement it ourselves. At this time, any server exception will not affect us, so our framework is based on the first three points.

It should be easier to understand the modification process of our company's server:

The previous framework of the server: there is only one HP. When the client calls the server, you only need to connect to the HP Server. The Encapsulation Format of business data is as follows:




The format of the returned json string is as follows:



Several fields are very well parsed.

The framework behind the server: ESB, ACC, and HP are two more at once. The ESB is fully controlled. That is to say, you cannot call HP when calling all your services, the ESB must be used, and the ESB obtains the data before distributing the data. ACC is an account center business, which is separated from the previous HP. That is to say, the previous business has an account center, the current execution process is first to ESB, and then the ESB is sent to ACC. After the ACC is executed, the result is returned to the ESB, And the ESB then returns the data to the client, besides, the ESB encapsulation data format is different from the ACC encapsulation data format. The ESB Data encapsulation is as follows:



ACC data is encapsulated as follows:




An additional layer is added, and the returned data fields are different. At this time, you will understand the importance of the client framework !!

Imagine that if our project does not have a framework, all the returned data will be processed in the Activity and the result will be obtained based on the data returned by the server, the server will be highly dependent. If the server is slightly changed, then we will die, and every Activity should be changed. The workload is huge and error-prone! Android itself emphasizes high cohesion and low coupling. This principle is also very suitable for the interaction between our clients and servers. The framework we want to build now should be considered most, it is not affected by the server as much as possible and does not cause major changes due to server changes. Therefore, I have summarized my own client project framework.


The general method of the Common class is as follows:

/**
*
* @ Param context
* @ Param method the name of the interface called
* @ Param data refers to the business data of the interface called
* @ Param urltype: the url of the call.
* @ Param second the standby field for calling the interface
* @ Return
*/
Public static ResponseBean getHttpResult (RequestBean request ){
ResponseBean response = new ResponseBean ();
String result = "";
HttpResponse httpResponse = returnResponse (request. urltype, request. data. toString ());
Try {
Result = EntityUtils. toString (httpResponse. getEntity ());
If (httpResponse! = Null
& HttpResponse. getStatusLine (). getStatusCode () = 200 ){
// Server UTF-8 encoding, converted to local GBK Encoding
If ("0". equals (Constants. isEsb )){
Result = new String (result. getBytes ("iso-8859-1"), "UTF-8 ");
}
} Else {// request failed

}
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
If (TextUtils. isEmpty (result )){
Response. code = "-1 ";
Response. msg = "Network request failed ";
Return response;
} Else {
Return parseResultToBean (result, request, response );
}
}


/**
* Parse the returned results of the http request
* @ Param resulthttp string returned by the request
* @ Param request complete data of the request
* @ Param response the encapsulated response Information
* @ Return
*/
Private static ResponseBean parseResultToBean (String result, RequestBean request, ResponseBean response ){
Try {
JSONObject json = new JSONObject (result );
If ("0". equals (request. packtype )){
Response. code = json. getString ("resp_code ");
Response. msg = json. getString ("resp_desc ");
Response. data = (JSONObject) json. get ("data ");
If ("1". equals (response. code )){
If (Constants. ACC_SYSTEM.equals (request. system )){
Response. code = response. data. getString ("resp_code ");
Response. msg = response. data. getString ("resp_desc ");
If (response. data. has ("data ")){
Response. array = (JSONArray) response. data. get ("data ");
}
Return response;
} Else {
Response. code = response. data. getString ("errcode ");
Response. msg = response. data. getString ("msg ");
If (response. data. has ("data ")){
Response. array = (JSONArray) response. data. get ("data ");
}
Return response;
}
} Else {
Return response;
}
} Else {
If (Constants. ACC_SYSTEM.equals (request. system )){
Response. code = json. getString ("resp_code ");
Response. msg = json. getString ("resp_desc ");
If (json. has ("data ")){
Response. array = (JSONArray) json. get ("data ");
}
Return response;
} Else {
Response. code = json. getString ("errcode ");
Response. msg = json. getString ("msg ");
If (json. has ("data ")){
Response. array = (JSONArray) json. get ("data ");
}
Return response;
}
}
} Catch (Exception e ){
E. printStackTrace ();
Response. code = "-2 ";
Response. msg = "Resolution result failed ";
Return response;
}
}

/**
* Encapsulate business data
* @ Param request
*
*/
Public static void packRequestData (RequestBean request ){
If (Constants. ACC_SYSTEM.equals (request. system )){
If ("0". equals (request. packtype )){
Request. data = packESBJsonData (request. context, request. data, request. method );
} Else {
Request. data = packCommonJson (request. data, request. context, request. method, request. system );
}
} Else if (Constants. HP_SYSTEM.equals (request. system )){
Request. data = packCommonJson (request. data, request. context, request. method, request. system );
If ("0". equals (request. packtype )){
Request. data = packESBJsonData (request. context, request. data, request. backupmethod );
}
}
}


We can see that I only need to build RequestBean and ResponseBean. For any changes to the server, we only need to encapsulate request data in parseResultToBean (parse the result to Bean), packRequestData (encapsulate request data) after the two methods are blocked, we will return the parsing result to the Activity. All the fields are defined by ourselves. The simple Parsing is as follows:

Private void cancleBind (final int type, final String openid ){
PDialog. show ();
ThreadPool. getInstance (). addTask (new Thread (){
Public void run (){
Try {
If (type = 1 ){
QQInfo. logout (mTencent, BandAccountActivity. this );
}
JSONObject data = new JSONObject ();
Data. put ("bindtype", type + "");
Data. put ("userid", Constants. userId );

RequestBean request = new RequestBean ();
Request. context = BandAccountActivity. this;
Request. method = "huicloud_remove_bind_sns ";
Request. backupmethod = "";
Request. packtype = Constants. isEsb;
Request. data = data;
Request. urltype = Constants. ACC_SYSTEM;
Request. res = "";
Request. array = null;
Request. system = Constants. ACC_SYSTEM;
Common. packRequestData (request );
ResponseBean response = Common. getHttpResult (request );
If ("1". equals (response. code )){
Handler. obtainMessage (4, type). sendToTarget ();
} Else {
Handler. obtainMessage (5, type). sendToTarget ();
}
Log. d (Constants. TAG, "=== BandAccountActivity === unbind result ="
+ Response. toString () + "= request data =" + request. toString ());
} Catch (Exception e ){
// TODO: handle exception
E. printStackTrace ();
Handler. obtainMessage (2, "network error"). sendToTarget ();
}
}
});
}


As you can see, you have basically understood the purpose of writing this article. Once again, we emphasize that the core idea of building our own client framework is to generate high client cohesion, reduced coupling with the server !!!

The respective attributes of RequestBean and ResponseBean can be determined based on your own needs. My current attributes are as follows:

RequestBean:

/**
* Context
*/
Public Context context;

/**
* Called Interface Name
*/
Public String method;

/**
* Standby fields of the called Interface
* When calling the hupeng system and passing through the ESB, the outer interface name is upeng_app, and the inner layer is the real business data name.
* This field is required when you call the paging system.
*/
Public String backupmethod;

/**
* Data encapsulation as required
*/
Public String packtype;

/**
* Service data of Apis
*/
Public JSONObject data;

/**
* The url of the API to be called
*/
Public String urltype;

/**
* Standby fields of the called Interface
*/
Public String res;

/**
* Alternate array type
*/
Public JSONArray array;

/**
* Which business system is called?
*/
Public String system;



ResponseBean attributes:

/**
* Request result code
*/
Public String code;

/**
* Request result information
*/
Public String msg;

/**
* Which method is used to parse the result?
*/
Public String packtype;

/**
* Result data
*/
Public JSONObject data;

/**
* Backup result data
*/
Public JSONObject res;

/**
* Multiple objects are stored in standby mode.
*/
Public JSONArray array;

/**
* This field is used when the result is string.
*/
Public String result;


When parsing the results, you only need to add your own resolution results in the parseResultToBean method of the Common class according to the method changed by the server, my small framework has also been trained in some projects and I feel very useful. I recommend it to you. If you have good suggestions, please feel free to contact us. My QQ: 1531074759, here is my understanding of the Framework. Thank you!

Related Article

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.