Reprint Please specify source: http://blog.csdn.net/ahence/article/details/56678126
Technology is evolving rapidly, the industry of various Android client architecture design, but we can not simply say which architecture is better, because it is meaningless to go out of business to talk about architecture, suitable for business is a good architecture. And the architecture is not static, with the development of the business, perhaps the original design of the architecture is not enough to support the current business, then need to change the previous architecture. The next step is to share the architectural design of our Android client, which may have some implications in the app's business development phase.
Layering and modularity
Layering and modularity should be a common understanding of any software development.
Layering of
In Android app development, you can usually be divided into the following layers:
- SDK layer: Mainly Android SDK and third-party SDK (possibly based on Android SDK or standalone SDK), these SDKs provide the core function support for the upper frame.
- Basic framework layer: Here the so-called basic framework, refers to the basic functions required by most apps, is the basis for the implementation of specific business logic. Mainly has the network request function, the picture loading and the cache function, the SQLite database management function, the log management function and so on, certainly according to the business logic support different, the basic framework layer function support also not necessarily the same, above several should be supported by most apps, Of course crash monitoring and common tool classes can also be categorized as this level.
There is no limit to the implementation of each infrastructure, such as network functions can use volley, okhttp or their own encapsulation to implement network request logic, for picture management function can use glide, Fresco, Picasso, or self implementation ... In short, each of the basic framework must follow certain implementation principles, maintain the independence of the functional modules, and specific business decoupling and provide good interface to the outside.
- Business Logic Layer: If the app architecture is likened to a high-rise building, then the above two layers are foundations. After the foundation is played, it can be played at any of the above, as to how to play, it must be combined with the actual business needs, different applications often have different business function modules.
On the other hand, the business function module is not exactly a side-by-side level, some business logic can be abstracted out, as a common function module, such as login, share, scan, statistics, and other business modules may call to these functions.
It is important to note that the SDK layer and the underlying framework layer are not immutable, but they tend to vary over a long period of time, and in general, they need to be extended when the underlying functionality does not meet the top-level business logic. Because the functional modules of the underlying framework layer are already functional-level granularity, scaling is often a module-level extension, usually with the addition of the underlying functional framework rather than modifying the original underlying functional framework, which also conforms to the "open-close" principle.
Modular
As for modularity, it is a finer-grained division for layering, with each layer subdivided into different modules, each function module follows the principle of "high cohesion, low coupling" as much as possible, providing only the necessary interface between functional modules.
For the underlying framework layer, it is visible and often divided by function. The basic framework layer is subdivided into the network support function, picture library, log system, database support module, if not enough to support the business development, may add additional basic function module.
The business logic layer is mainly determined by business requirements, such as scanning function, e-commerce, express query and other modules. The modularity of the business Logic layer also has a driving factor, that is, the general function of the encapsulation, which we should all have experience, as the app business logic increases, different business functions may use the same function, such as user login, sharing function, we do not want to be in every need to replicate the relevant code, Therefore, it is necessary to extract common functions into modules independent of the specific business requirements, such as login module, share module, implement common business logic inside the module, and expose the calling interface at the same time, different business simply call the common module.
Business Data Process Design
Because of the difference of business logic, data processing logic or network framework, it is believed that each application has its own set of data request flow. The most straightforward is the method of invoking the network request from activity or fragment, and then returning the result to the activity or fragment through a callback, although the process is clearest, there are several serious problems with this approach:
- Network data is returned directly to activity or fragment, and subsequent operations such as parsing, filtering, converting, caching, and so on, will greatly increase the burden of activity or fragment.
- The amount of code in activity or fragment is soaring, logically complicated (not only the logic of the view but also the logic of data processing)
- From the point of view of the whole application, every page and even every interface needs to repeat the same redundant work, can be abstracted out completely.
The above design ideas are to be discarded, combined with their own business and architecture evolution, we have not followed the MVP, MVVM, but designed the following set of business data request process:
First, the view layer typically behaves as activity or fragment, and the data request is initiated by the view layer, and unlike the above, the view layer does not deal directly with the network framework, but instead sends the data request to the data broker layer dataagent. It is important to note that there is no direct communication between the view layer and the data broker layer, but rather that a message scheduler is inserted into the Messagescheduler relay. The advantage of this is to decouple the view layer from the data broker layer, the view layer does not need to pay attention to the specific implementation of the data agent layer, with the Messagescheduler, the view layer to do is to send a data request message, and then can silently wait for a reply message, The reply message comes with the data object that is ultimately needed so that the logic of data processing is removed from the view layer and the results are displayed directly on the UI. In this way, in general, activity or fragment 3,500 lines of code can be done, UI logic or interface logic (such as a page with multiple interfaces) more complex code is basically able to control the amount of 1000 rows or so, the logic is very refreshing.
After the message scheduler forwards the request message from the view layer to the data broker layer, dataagent resolves the data request type datatype (which corresponds to the specific data object model), the necessary parameters (interface parameters, whether the cache results are required, page numbering, and so on), and then performs the specific operation:
- If you are fetching cached data, Dataagent sends the request directly to the cache module. The cached data can be either the initial JSON data or the data object model resulting from the parsing process, which can be configured according to the specific requirements. If the JSON is taken from the cache, then the dataagent must parse and process the corresponding model, if the model is taken from the cache, do not do the processing, and then send the model package back to the message scheduler, and then distributed by Messagescheduler to the specific requestor, such as activity or fragment.
- Since there are many sources of data from Android, if data comes from persistent storage, such as SQLite or file, it is still unified by dataagent to communicate with them, get the data and process it back to the view layer via Messagescheduler.
- The most common is to get the data from the server, in this scenario, Dataagent will interact with the network framework to provide the parameters obtained from the Messagescheduler to the Network framework construction request URL. As for the network framework using volley or okhttp or whatever, the network framework is responsible for requesting data from the server, which is usually returned in JSON format. After Dataagent receives the returned JSON data, the JSON data is validated against the parser after datatype, and the parser parses the JSON into the model required by the view layer. Of course, the data parsing process may accompany the data filtering, transformation and other logic. It is also important to note that there is a need to cache the data based on the requirements of the view layer, either cache JSON or model. After a series of operations, the final model is obtained, and Dataagent sends it back to the view layer via Messagescheduler.
Of course, because the data request process is time-consuming, the above steps are a thread pool that is gone, which is not noted.
Data Agent Layer
Dataagent mentioned earlier, its main role is a series of operations on the data, including the actual data requests, data parsing processing, data caching and other logic. The process of getting JSON data from a server-side interface and processing it:
From the dataagent, the approximate workflow is:
- Dataagent sends a real data request to a data source, which may be a cache, SQLite, or a file, but usually gets the data from the server, so dataagent sends the data request to the network framework layer and waits for the data to return.
- Because the data source is different, the returned data may also be different, which is simplified to two kinds: raw JSON or model.
- When the dataagent gets the data, it begins a data processing process. Take the JSON data from the network request for example, first the data of the JSON is checked, check the validity and correctness of the data, if the data check pass, then according to the requirements to decide whether to write the cache, and then the data processing (such as precision processing, data splicing, data clipping, etc.), Finally, the data is parsed to get the model required by the view layer. If the data check does not pass, then try to read from the cache, read from the cache will also need to verify (check the data's timeliness, validity, correctness), check the same after the data processing, parsing and other processes. If the cache reads from the model, then the process of data processing and parsing can be omitted. After getting the final model, Dataagent sends its package to Messagescheduler. In addition, Dataagent also has a certain fault tolerance function, because no data source can guarantee to return legitimate data, if the data error is not fault-tolerant processing, then it may not be resolved to the corresponding model, resulting in the view layer no data or even exception. If neither the interface nor the cache can return the correct data, dataagent needs to do special processing to ensure that the view layer can give the user feedback.
Business View Logic
While different business pages have different view logic, this is illustrated by an example of the most common page in an application, assuming that the page has a list. We all know that the ListView (here is a generic, probably everyone is using Recyclerview) work, it needs to viewholder to fill the view, need to adapter to fill the data, If each interface that needs a ListView maintains its own set of Viewholder and adapter, then the page logic becomes bloated.
We do this in practice:
- Encapsulates a adapter public processing class that provides a variety of constructors with a type parameter that indicates which viewholder to use.
- Encapsulates a Viewholder abstract class that defines the logic of the data set and is implemented by the specific viewholder.
- Build a class called Viewholderfactory, as the name implies that the main role of the class is to build Viewholder, which mainly provides two methods Createviewholder () and Createconvertview (), where Createconvertview () is an intermediate method for generating Viewholder.
- In the GetView method of adapter, according to the type parameter above, get the concrete viewholder implementation, invoke the logic of setting data.
After the above encapsulation, the view layer only needs to pass a type parameter to the adapter public processing class to get the corresponding adapter, and when the data is returned to the view layer, the data is passed to the adapter public processing class, and nothing else can show the list data. Once the logic of a lot of code implementation is drawn from the view layer, the view layer will be able to complete a list with just a few lines of code.
Hybrid frame
Since the birth of Android, there has been native app and web app dispute, these two development methods, although each have advantages and disadvantages, but the native app has prevailed. Over the past one or two years, more and more Web pages have been used in mobile applications, while pure native have been relatively less. However, the pure web app is not widely used because of its rendering efficiency, performance problems, and restrictions on hardware calls. So a compromise solution became mainstream, namely the hybrid App.
The so-called hybrid App, which is a hybrid development approach, is partially developed using native, and some features are developed using H5. To take advantage of web development and avoid its drawbacks, not all business functions are suitable for web-based development. In our application, H5 is mainly used in the following areas:
- A page of timeliness, such as a holiday event or game page, seconds Kill, or group purchase page.
- Use instructions, announcements and other partial display, less interactive pages.
- Pages or modules that are frequently updated, have fewer interactions, and do not involve hardware calls, such as the e-commerce home page display and the Redemption module.
As of now, the proportion of Web pages in our app is up, about 25% of all functions. The benefits of using web development are obvious, supporting a variety of UI view effects, saving development manpower (Android, ios sharing), online bug fixes without app releases, and more.
To meet the Web page requirements of the app, we expanded a hybrid function module at the base framework level. The framework is mainly self-encapsulated Android native WebView control, and is divided into different levels of packaging, can be used flexibly as required, core features and features are as follows:
- Support Complete Web pages, that is, the entire content of the page is H5 implementation, the external container for activity or fragment.
- Support for partial web pages, that is, the content of some pages is H5 implementation, can be used alone with custom webview or embedded fragment.
- Define a more complete set of interactive protocol, support native and JS call each other, a typical scenario such as H5 page click Jump Native Function page (support the parameter), JS Invoke Native dialog box or toast, and Java can also call JS function. Based on this set of interactive protocols, it is essential to meet the needs of web development in everyday apps.
- Avoid the JS injection vulnerability.
- Supports scenarios where HTTP and HTTPS are mixed in the same Web page.
- Exposes interfaces to the business logic layer and can customize webviewclient and webchromeclient as required.
- External interface, can be based on demand control scaling, cookie management, cache management, hardware acceleration and so on.
- Tested and explored, compatible with a variety of Android devices and versions.
Although react Native later appeared, due to the limitations of the learning cost and its Android version, combined with the human resource reasons of our own team, we have not yet been formally used in the application. The hybrid framework is an important part of our architecture, as hybrid is still being developed and its weight is increasing throughout the application.
Message Dispatch Center
In the design of the preceding business data flow, a message scheduler is inserted between the view layer and the data agent layer--messagescheduler,messagescheduler The main function is to manage the message and message dispatch.
The core principle of messagescheduler is to maintain a hash table that, when receiving data requests from the view layer, uses a unique key to save the initiator to the Hashtable so that the initiator can be found later when the Dataagent return data is received. After storing the information of the initiator of the message, that is, sending the data request to the Dataagent, multiple data requests can be parallel, mainly in the thread number control mechanism of the threads pool. After Dataagent returns the data, Messagescheduler finds the original requestor based on a unique key, and also uses the message mechanism to return the request result to the view layer while clearing the element in the hash table. It is as follows:
Message Dispatcher
Now that you have the message dispatch mechanism, you need the message dispatcher, MessageDispatcher, to be responsible for sending messages.
MessageDispatcher essentially leverages the messaging mechanisms of Android to encapsulate and scale business requirements. Look at the Android framework layer source code will find that in fact, the Android framework itself has many places to use the message mechanism to communicate, Android message mechanism can be in the module between the page, the thread between the communication, Messenger communication can even be used between processes (Messenger is using the messaging mechanism and, of course, other interprocess communication methods).
The MessageDispatcher function is simple and supports two ways:
- For Point-to-point communication, such as two pages, the communication target is unique, as mentioned above, sending a data request message from the view layer to the message scheduler.
- The opposite of the communication, similar to the broadcast, but also a bit like Eventbus, a message issued, usually registered (or called subscription) of the page can be notified, or further through the tag control to achieve one-to-one transmission.
It is as follows:
Module Routing Center
A complete application, the inevitable between the module, the function between the page jumps. Of course the jump can be achieved by intent where needed, but this is not a good solution, obviously the coupling degree between different modules or pages is increased. Our principle is to decouple the module and the page as much as possible, so we designed a module Routing center, and all the page jumps in the app are controlled by it.
The core principle of module routing is to uniquely encode the function pages, which can be defined in the application with the product version, and the previous version is guaranteed to be compatible. This makes it possible to send the encoding of the corresponding module page to the module routing center anywhere in the application, which is responsible for opening the target page by module routing.
The following points need to be noted:
- The function page encoding in the entire application must be guaranteed to be unique
- If you open some feature pages in addition to specific coding, you may also need additional parameters. If you open the Product Details page, you need the product ID in addition to the code of the Product Details page, and the module routing needs to support additional parameters.
- Module routing supports opening a Web page, that is, the hybrid page also supports the specific encoding above, so clicking on the Jump native page on the Web page uses the protocol that is supported by the module routing.
The benefits of using module routing are:
- Massively reduce the jump intent in your app
- Decoupling between modules and between pages
- Adaptable change, unified management, easy to modify
Other
Log system
Logs are an important part of the development process, even during the run. Of course, Android provides a log-related API, but it is not recommended for this line of sporadic use, otherwise if you want to control the tag or close the log is very troublesome. It is recommended to simply encapsulate the log API or use the existing third-party log library, separate the log function, provide a unified call interface, level control, switch control, which is easy to debug and easy to manage, but also for the entire application code clarity to make a contribution.
On-line crash monitoring
Crash monitoring on line application is an important method to improve application stability and optimize application performance. We have built a small global monitoring system, mainly by the following functional features:
- Invisible to the user, no user awareness
- Global registration to enable monitoring
- Capture line crashes, save to local file
- Online Crash information upload the server as a certain policy, and delete the local file after uploading
- Crash information mainly includes Android device information (such as phone model, system version, etc.), app version number, exception information, etc.
After the server receives the uploaded online crash information, it also notifies the developer by email, so that the developer can fix the exception in a timely manner. Online Crash monitoring System although small and simple, but the role is very important, the use of online crash feedback can effectively improve the stability of the application, it is recommended that in the application design must set aside a position.
Statistical systems
Believe that most applications have a statistical analysis of the background, you can count the application of daily life, PV, UV or other user behavior, there may be a part of the application is the use of third-party statistical functions, such as Friends of the league. In combination with the company's BI department's statistical needs, our client has designed a statistical program for Android and iOS two clients. The reason why we don't use third-party statistics is that we are not free to customize according to demand and the data is not in our own server, on the other hand there is a slight risk of data leakage.
The client-based statistical system mainly consists of three functions:
- Data acquisition
- Data storage
- Data upload
For data collection, mainly for the statistical department's needs, such as collecting equipment information, location information, app launch time, PV, UV, and even user behavior, such as click, Switch tab, page flow tracking.
In order to avoid uploading data after each acquisition, it is necessary to store the data, to save the collected statistics to local, and generally use SQLite. Then use a certain strategy to upload, such as data accumulation to 50 or when the application switch to the background to upload.
For data uploading, in addition to the timing of the upload selection strategy, but also to follow a certain structure of the field, the structure can be defined according to the requirements of the data Statistics Department. The data upload process can also use the previous data request framework, except that the return value may be a success hint.
Based on the above functions, our custom statistical function module provides a convenient calling interface and supports flexible scaling, which can now perfectly support the daily statistical requirements, and the invocation is very simple, just insert a line of code where the statistics are needed.
The strategy of domain name hijacking
Recently encountered domain name hijacking problem, is really a headache, on the other hand also shows that our traffic caused operator attention. There are several options currently in the mainstream:
- complain to the operator. This method is very passive and ineffective, with complete control of the operator.
- Use Httpdns. This method uses HTTP direct to obtain the best IP, bypassing Localdns resolution, it is a complete solution to the domain name hijacking.
- Use domain name attempt first, domain name fails and then use IP attempt. This scenario is a disaster tolerant solution and does not prevent domain hijacking.
In theory, the second is the best solution, but since Httpdns is a third party service, there is no guarantee of the effect, plus the cost of pay and access costs and other factors, we have temporarily adopted a third disaster recovery program, the main implementation of the following logic:
- Apply pre-built-in IP.
- Get the latest IP every time you start your app and save it locally to your app.
- When requesting data, use the domain name to go through the normal logic, once you encounter a suspected hijacking problem, use the local IP for direct connection attempt.
The above steps are in fact a loophole, such as the start of the interface to obtain the latest IP if hijacked, then can not get the latest IP, if just the same time the server IP also changed, so the pre-built IP has been invalidated, at this time there is no way. However, the probability of satisfying the above two conditions is relatively small, so the scheme can be used to solve a large part of the domain name hijacking problem. In addition, the IP obtained from the server, if there are many, but also need to add a number of policies, namely, load balancing, access speed, stability, network operators and other factors, how to determine which of the client is the optimal IP, of course, this can be optimized, but first of all to ensure that users see the page data may be more important.
The above strategy for domain name hijacking cannot itself be a single module, and we integrate it into the expansion of the network framework.
Summarize
As mentioned above is a core part of our Android application architecture, you may find that there are no fancy, trendy gadgets, no MVP, no rxandroid, no plugins, no hot fixes ... But that is how it still supports billions of users. There is no perfect architecture, only in line with their own business architecture, the above architecture has many shortcomings, we are also in a selective, step-by-stage reconstruction, and with the expansion of business needs, the architecture will continue to evolve, and finally hope that this article will bring you a little reference significance.
An Android client architecture design sharing