[Android Pro] developing first-class Android SDK

Source: Internet
Author: User
Tags least privilege asymmetric encryption

CP from:53558011

This article has been authorized by the public number Guolin_blog (Guo Lin) Exclusive release

Since the departure of the previous period, because the personal matter has not chosen to work, also led to the original article and did not produce on time. Recently, personal things have been sorted out almost, just a lot of friends to ask about the SDK development, here is a simple comb, hoping to help you.

Now more developers are keen on application development, very few developers have the opportunity to engage in SDK development work, and the market on the SDK development introduction of the few articles, so that the SDK development is relatively difficult and very boring work, today we will briefly talk about the SDK development of what point.

About the SDK explanation what is the SDK

Before starting the text, let's start by talking about what the SDK is.

The SDK is an abbreviation for the Software Development Kit, translated as a "software development kit", typically a specific package, framework collection, etc. written to assist in the development of certain types of software, and the SDK typically contains relevant documentation, examples, and tools.

The SDK can be divided into the System SDK and the Application SDK. The so-called System SDK is a collection of development tools for specific software packages, software frameworks, hardware platforms, operating systems and other CV applications. The application SDK is based on the System SDK developed independent of the specific business and has a specific function of the collection.

For example, when developing Android apps, we use the System SDK (Android SDK) provided by Google, and the Friends League SDK that we often use, the Aurora SDK is based on the System SDK.

After clarifying the concept of the SDK, let's talk about these three concepts: library,api,framework

What is a library?

The library, which is what we call libraries, is usually a collection of groups or groups of classes, usually a specific implementation of some of the features in the application or enhancements or additions to the existing functionality of the system. The most common thing for Android developers is the support Library, In addition, we often use a variety of Network Request library (Okhttp,volley), database operations, image loading library (glide,imageloader) and so on.

What is the framework

The framework, which is what we call frameworks, is usually the skeleton of a system or application, and many times it manifests itself as a set of abstract constructs and methods of interacting between instances of artifacts. Therefore, it can be argued that the framework prescribes the architecture of the application, clarifies the overall design, Writing component dependencies and control processes. Note that the framework is not exactly the same as what you know about the Android framework, and you can think of the framework as embodied in the Android framework and implemented.

What is an API

API is application programming Interface, also known as the Application programming interface, is the agreement that the different components of software system converge. More generally speaking, the API is the method or function that we commonly and write.

Summary

Having clarified the concepts mentioned above, it is now possible to describe the relationship between the four:
The SDK mainly contains the three parts of Framework,api and library. The framework defines the reusable design of the SDK as a whole. The functions and dependencies of each functional module of the SDK are defined. One of the functional modules is the library. Internal communication between modules and external communication of the SDK (interface for external services provided by the SDK) is done through the API.

The complete SDK should also contain a large number of examples and other tools. For example, in the Tools directory of the Android SDK, a number of ancillary development tools are available.

For us, in most cases, the SDK is developed for a specific business need so that it is being provided to other demand parties as a third party. For example, Baidu push the SDK mainly to achieve message push function, demand side only need to integrate Baidu Push SDK can make their own application with push function.

Now that we've covered the main components of the SDK, we'll focus on the implementation goals of the SDK and some of the core points in the SDK architecture.

Talking about the goal of SDK realization

The concepts that are common in development are described above, and now talk about the implementation goals of the SDK. Any application should have: simple and easy to use, stable, efficient, lightweight, the SDK as a specific application of course is no exception.

Simple and easy to use

According to the "Ames Razor" theory, a good product should be simple and easy to use for third-party users, without changing the user to spend too much time learning. The same applies to the SDK-sdk should not have too much code intrusion on the host application. There should also be no complicated and frequent access work. For example, when a developer needs to use the SDK's services, just add a line to the code for the reason. Common SDK initialization is as follows:

public class Ad{    @TargetApi(9)    public synchronized static void init(Context context, SdkParams params) { //省略多行代码 }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

When we need to use the SDK's services, a single line of code enablesAd.init(this,params)

To ensure that less code intrusion mainly in the external provision of services to fully consider the user's use of the scene to design a good API. A good API should be defined in a way that the vast majority of developers expect-semantically demanding, simple and reliable to use.

A good API is first and foremost simple and reliable. In the case of normal use, it manifests itself as stable and reliable execution, and in exceptional cases it manifests as a timely notification to the user of the use of errors. For the first time, following the consistent rules of the clear, and all APIs showing a consistent style is undoubtedly good news for development.

Stability

From the perspective of the SDK users, we expect that the third-party SDK services should be stable and efficient, reflected in the provision of stable and reliable services, without compromising the stability of the host is sufficiently efficient, which requires our SDK designers to design and implement the SDK as far as possible to do the following:

    • Externally providing a stable API.SDK API once determined, no very serious conditions can be changed. As a service provider, the cost of changing the API changes is very high.
    • Provide a stable business to the outside. After a stable API, there must be a stable business to support.
    • The SDK runtime is stable, and as a service provider, we must ensure that the SDK itself runs stably and that the access party does not cause instability in our SDK.
    • Version stable update. The SDK version iterations are very slow compared to apps for ordinary users. And you need to shield the developer from the iterative process as much as possible, so as not to introduce unnecessary adaptation overhead to the developer.
Efficient

Whether it's a common application development or SDK development, you should consider performance issues, and the SDK designer should focus on the following issues:

    • Less memory footprint. Without multiple processes, the SDK service and the host program run in the same process, in which case it must be required to limit the footprint of the SDK memory, not because our SDK consumes too much memory resources, resulting in shorter application survival time.
    • Less memory jitter. With less memory, the SDK designer must deliberately reduce the memory jitter problems caused by repeated GC.
    • Less power consumption. Although there are many times when it is not possible to make a good trade-off on power consumption, there are still some ways to refer to it, such as reducing the time it takes to use the battery. For example, when using location services, it is not required to use network positioning rather than GPS positioning for very high precision.
    • Less traffic consumption.
SDK Overall Architecture Design

The SDK's implementation of the architecture determines the subsequent maintenance difficulty of the SDK, so it is necessary to make some simple explanations for some of the points in the SDK's overall architecture.

Modular development

Split the system into smaller modules according to a single responsibility, each of which remains relatively independent.

The modules communicate with each other through protocols or interfaces to reduce dependency coupling. The module is implemented in accordance with several principles of design to ensure that the module itself can be flexibly implemented

For modern development, modularization is a common means, from the macroscopic point of view, the module is the smallest unit of the system.

Modular development

Component development is also a Laosheng Changti concept, but in my personal sense, components are encapsulated in logic and have a single portability. For example, you can make a log record a component, and then it can be easily applied to different projects. For Android developers, Android Each UI control provided is also a component, such as Button,textview.

After defining the concept of components, component development is not difficult to understand: the so-called component is to divide the entire project into multiple modules, several modules or a single module as a component, in the development process we can be in parallel development of each component, and finally released by relying on the integration of components into a complete application.

So why use component?
As Android matures, the app business is becoming more complex, and Android engineering is becoming increasingly large, with code lines of a hundred thousand of already the norm, and several issues are highlighted:

    1. Any modification of the project will result in the recompilation of the entire project. The deepest memory is the early in the absence of components, the huge project often requires more than 10 minutes of compilation time, a cup of tea time out, many times, have to wait, Although it is now possible to use the buck from Facebook and Feeline from Ali to speed up the compilation process, it is still not enough.
    2. A large number of repetitive or redundant sub-modules throughout the project, the business coupling is very high, reaching. This causes "The old man dare not change, the new person cannot change", because who also cannot predict after making the change, will have what influence.
    3. Collaborative development is basically impossible, and God knows what to do with each other. It's even more painful when the code is merged.
    4. Not easy to test. Highly-coupled business and modules lead to the inability to test, only quickie.

With the introduction of components, the problems encountered above can be solved. In the SDK, it is based on the actual situation of the component, for example, we will share the functional components, can easily support the sharing of multiple channels, when the need to update the sharing function, it can be compiled and tested separately.

Through the component, we can also easily implement the customization function of the SDK, by writing a compilation script, we can decide which components are dependent, and eventually merge into the complete application. The principle of a customizable sharing component, such as the one provided in the Friends League, is the same.

Plug-in development

What is the plug-in development here does not introduce, on the one hand plug-in is not a new concept, the other is the plug-in so far at the theoretical level has been very mature, do not want to 15 read the beginning of the study when the data is relatively small.

Why plug-ins are used in the SDK? The SDK is different from the normal application and cannot be updated frequently, so as not to make developers feel that the SDK is unstable or to allow developers to integrate frequently. The SDK seems to change slowly, but it changes frequently. As far as the previous advertising SDK is concerned, sometimes it is necessary to collect or update the anti-cheating module in some type of model. It is very cumbersome to solve this problem before using plug-ins. But after we've used the plug-in, it's easy to solve the problem: we divide the SDK into two parts: the host and the plugin. The hosts only provide the necessary service interfaces to the developer. A custom plug-in loader is provided. The core logic is present in the plugin. When data acquisition is required, only the developer should develop a data acquisition plug-in and assign it to the specified device, and when it is necessary to fix the SDK flaw, it is only necessary to release the new plug-in package.

By using the plug-in scheme in the SDK, you can effectively block the process of manual updates to developers. The host is relatively stable, once determined, generally does not change, and subsequent business changes only need to be supported by the update plugin.

In addition to the use of plug-ins to resolve dynamic updates, by dividing the entire project into hosts and plug-ins, you can implement parallel development and separate compilation of the host, and can effectively solve the limit of 65535 of the method. Before we use plug-ins, our entire project is a huge project of many components through dependencies, Had to pass

SDK initialization

Unlike application development, in many cases the SDK does not have its own contextual context and must be provided by the application. Common practice for SDK initialization: Ad.init(Context context,AdParams params) We often recommend that developers remove this method from the application of OnCreate () in the application component, which means that the initialization process is synchronous, and if the SDK itself is initialized for a long time, it can affect the startup speed of the application.

In this case, the designer of the SDK must address the issue. The SDK service is typically further divided into core services and ancillary services, and the SDK initialization time is reduced by means of parallel initialization and deferred initialization. Once in the Advertising SDK I was responsible for, Developers feedback Our SDK startup is slow, through the entire SDK START process analysis, we will plug-in loading services and cloud control services in parallel initialization, and for the like log service with Yan value initialization, through this means effectively reduce the initialization time

Cloud Update Control

Cloud control Services as a service-side control client is very important in the SDK development, the SDK development can not support the plug-in, but must provide a cloud control service, so that the server can control the SDK, such as when the data collection is not required, can be the cloud control service to turn off the SDK collection function, Turn it on when you need it.

Cloud-controlled services are essential to the SDK itself, which is based on plug-in development.

From the perspective of implementation, cloud control services are divided into active and active clients. Server-side initiative refers to the service side will be the latest cloud control switch information pushed to the SDK, and the client initiative is the SDK before the operation will be the first request cloud control information. This is very easy to understand for students with push development and management. Just like to implement the message push feature, we can use the client-side rotation as well as the server to keep long connections for message push.

Security SDK self-security

In order to differentiate the users and pick up the security of the SDK itself, we typically assign API keys and API SECRET,SDK to developers to read the developer-configured API key and API secret and use it for subsequent network traffic. This is a very common practice, For example, when you integrate the Aurora Push SDK, it may require you to provide API key and API secret, if not, you need to apply to the official website.

Core Logic uses C/

For the sake of security, the data encryption class, the module algorithm class should adopt the NDK development, encapsulates it in so file. There are a lot of developers who don't understand why this can enhance security. Here's a simple explanation. Because. so files are compiled from C + + files, Compared to Java's anti-compilation files, the readability is worse, and most of the Android developers do not have a deep C + + ability, so to a certain extent increased the ability to be cracked.

Communication encryption

According to the actual situation of the communication protocol encryption, in particular, the use of symmetric encryption or asymmetric encryption, you need to choose based on the actual situation. Also, use HTTPS as much as possible instead of HTTP.

Device Safety

In many cases, such as the Ad SDK, some developers will use the virtual machine to brush ads, so it is necessary to judge this situation. Once the SDK detects an illegal request, it can take two scenarios, one is the SDK denial of service, the other is the normal service, and the SDK uploads the cheat information to the server. So that the backend service directs the exclusion of data.

Reduce transfer data size

When designing the data protocol between the SDK and the server-side communication, you need to consider the actual situation, but there are a few suggestions that deserve our acceptance:

    • If there is a requirement for the data size of the transfer, it is recommended that the data be compressed.
    • Protocols such as JSON/XML/PROTOBUF can be used, and a custom binary protocol can be considered if they are still not satisfied.
Select support Minimum System version

As the designer of the SDK, there is a big problem that we have to consider the minimum version of the system supported by the developer application, but before the SDK is released, we don't know what kind of developers will use the services we provide, so in order for the SDK to support a wider range of devices, We need to reduce the minimum supported version of the system. For example, insomnia now the mainstream system version is Android 5.0, then for the SDK, at least to support Android 4.0, or even Android 2.3.

Lowering the minimum supported version looks easy, but we have to do more to make sure that the SDK behaves consistently (in general, we detect the current system version inside the SDK to determine which methods can be called). The more brutal truth is that we spend a lot of energy to support 2.3, However, the request volume from the 2.3 system version is not even 1%.

Rights Management

Any development in Android is not open to permission requests. As the designer of the SDK, for the permission to follow "if unnecessary, no need to add", in other words is the use of permissions, do not add up, this is what we call the principle of least privilege, the same principle applies to common application development.

Some of the earlier features require some permissions when you first touch SDK development, but the functionality is cut off later, but the permissions are forgotten, which leads to situations where unnecessary permissions persist.

In addition, too much permission to apply, will allow developers to doubt your purpose. For example, what do you want to do when you apply for camera permissions in an advertising SDK? Well, I doubt you're videotaping me ... okay, here I am just kidding.

Also, from Android 6.0, Google has changed the policy for permission requests, so it needs to be adapted individually.

Log service

The log service is a basic service regardless of the system size. A good log service can help us quickly identify problems, locate bugs, and get solutions to problems.

The log service of the SDK is not much different from other common log services, but the following points are guaranteed:

    1. The log service can record valid information and point to the key location of the SDK.
    2. Log service to upload log information to the server, to ensure maximum reliability, can not occur after uploading failed to discard the log.
    3. The log service does not affect the excessive performance impact on normal operating processes. The log information generated by the SDK is often very much, so you must consider the overhead of log IO operations.
Delve into API design

API design in any development is very important, many times the quality of the software is not good in the design of the API can be reflected. In a common application development, the API will only flow between app developers and will not be exposed to other people who are not developers of this application, but the SDK serves as a service You need to expose a subset of the APIs to the developer. Usually we call internal APIs an internal API, and what's open to developers is called the SDK API.

The use of the two scenarios is different, but they follow some general design rules, which cannot be detailed here, only the 11 principles I think need to focus on:

The method name can indicate its purpose

The method name is the first channel to understand the meaning of the method. A good method name is the first to be able to show others the function, the advantage is to reduce unnecessary communication costs, for developers, there is more than direct reading code more intuitive.

Verification of the legality of parameters

It is important to verify the validity of the parameters, and do not take it for granted that you can use runtime exceptions instead. When the legitimacy check does not pass, there are different processing strategies for different method permissions, respectively:

  • For exposing methods to show checks for throwing exceptions, and using Javadoc's @throw to explain why the exception was thrown
  • For private methods to check the legality of arguments by asserting the way
  • Check the legality of the parameters of the construction method so that the object is in a unified state
    It is important to note that if the cost of the inspection is too high, a comprehensive consideration is required, such as if a large list is accepted, the cost of the inspection may be significant
method to clarify its single function

A method should have a single function and do as little as possible, but more specifically. This is also the single principle of responsibility that we often say. It is important to remember that rather than providing a chatty approach, the experience of positive chatty tends to change and the likelihood of risk is higher, Therefore, it is better to provide a smaller method to use in combination

Method Exception Problem

For methods that need to be exposed to developers, it is necessary to promptly throw out exceptions to help developers find problems during the compile phase, and for runtime exceptions, the SDK designer must ensure that such exceptions do not cause problems with the host program and need to inform the developer.

Method Permission Control

The permissions of the method are also important to consider, and the SDK designer must also consider from a security and business perspective which methods are public, which are not public, and which are static.

Avoid too long parameters

Too long parameters can cause memory difficulties and need to be treated with caution. In the case of too long parameters, there are other workarounds to consider:

A. By using the builder mode to achieve
B. By using auxiliary classes, it is common to use static inner classes, as described in static internal classes
C. Encapsulating multiple parameters into a class object
D. By splitting parameters into parameters of multiple methods

Cautious use of method overloading

Overloading should not confuse the user, that is, it should not be the case: the same argument, but the developer is not clear which method will be executed. In other words, do not create ambiguity.

It is also important to note that there is no case where the parameter type is automatically converted to run in another method, and I have seen the code review in the list remove(Object) , and remove(int) make sure that you do not make a similar mistake. Although you can use overloading in Java, But I don't recommend it, especially if you don't overload variable-length parameters, rather than using different method names to replace them when you need to overload them. The classes provided in Java ObjectOutputStream give us a good demonstration: its write has a variant for each basic type, such as writing out characters, Writing a Boolean, we found that the designer did not use overloading to design it, write(Long l) write(Boolean b) but rather to design it as writeLong(l) , writeBoolean() .

For constructors, you can override overloads by using a static factory.

Careful use of variable-length parameters

In most cases, variable-length parameters are not required, and variable-length parameters are recommended when the parameters of the general method are more than 5. In the case of other non-variable length parameters, I think the variable length parameter is placed at the end of the formal parameter list.

Avoid methods returning NULL directly

Do not return null for methods that need to return an array or this collection. For example, we go to the bakery and buy some bread. If it is a normal state, you should not return NULL, but instead return an array or collection of length 0.

A protective copy if necessary

When a class accepts an object from a client or needs to return an object to the client, it is necessary to make a protective copy of the object if the class does not tolerate any further changes in the object. It is also important to note that the validity of the parameters is tested after the protective copy.
It is important to note that if the object requiring a protective copy is very large, such as the existence of a Chendovan object in the list collection, it is necessary to weigh the processing.

These 11 principles are what I promote in the team and require strict adherence, and below, the 10 principles will be explained separately.

SDK Development process

About the SDK development process, I will write from the following three aspects: how to co-development of the team, the second is the continuous integration of the SDK, the third is the SDK multi-warehouse splitting and management.

These three aspects will be in another chapter of the show (when the specific time to finish is not yet determined)

SDK version Management Policy SDK version number naming and modification principles

The SDK version number name and our previous naming rules are not very different, through 4 parts, the format is:
V Major Version number sub -version number stage version number _ Date version number plus the Greek version number. For example V1_1_2_161209_beta .

Greek letter Version Number description
    • Alpha version: Internal Beta, this version indicates that the software at this stage mainly to achieve the main function, the bug is relatively more, need to continue to modify, usually only in the internal circulation and not open to the outside.
    • Beta: External beta version, this version relative Alpha has been greatly improved, there is no serious bug, but there are still some defects, need further testing to check and eliminate the bug.
    • RC Version: This version is quite mature and there are no bugs that cause errors. It's just like the official version.
    • Release version: This version means "final version", which is the final delivery user or a publicly released version, also known as the Standard Edition. It should be noted that this version is released with R in place of the release word.
Version number modification rules
    1. Major version number change: When the function module has a large change or the overall structure changes
    2. Sub-version number change: When the function has a certain change
    3. Stage version number changes: usually bug fixes or minor changes, depending on the feedback, you need to publish the revised version frequently.
    4. Date version number (161209): Used to record the current date of the modified item, and every day changes to the item are changed to the date version number.
    5. Greek alphabet Version number: This version is for labeling the current software is in that development phase, and when the software enters another phase, it needs to be modified.
API version Management

Unlike the general Application API version management, the SDK designer needs to focus on the management of the SDK API. In principle, once the SDK API is publicly released, its state (signature and implementation) should be immutable.

For special cases the change of the API, the need to adhere to the "open and close principle", that is, a class, modules, methods should be extended development, the modification is closed. This requires that we do the following:

    1. When you need to tweak the SDK API, you prefer to add a new method instead of modifying it on the original method. For new methods that implement the same functionality, try to be as compatible as possible with the original method.
    2. When certain methods need to be abolished, the @deprecated logo needs to be used prior to the release of the official version, with alternatives and time wasted (usually the SDK version number)
Access to documentation and API documentation version management

The access documentation is used to tell the SDK user how to use the SDK, the detailed steps used and the possible issues, and each company will have its own set of rules, which does not require much explanation.

In addition, access documents are usually divided into two parts: internal and public. The internal version is typically used for internal developers and testers, with more detailed information, while the public version is for developers and some information that is omitted from the internal version.

API documentation is actually a more detailed description of the SDK API, similar to Java API Doc, can be generated directly with the JDK Javadoc, of course, Android Studio also provides a convenient way to build.

The changes typically occur when the SDK version changes, whether it is an access document or an API documentation. When the SDK changes, the document must be updated, and the SDK update does not show that the document does not match.

Integrated Demo Version Management

The integrated demo is usually a simple app that shows how to quickly access the SDK. Changes to the version change policy and SDK version are consistent.

Summarize

SDK development needs to pay attention to a lot of points, each point can not be completed with few words, the latter will be based on the gradual replenishment.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. 53558011Article Tags: SDK third-party frameworklibrary experiencePersonal Category: Vernacular Android developmentcolumn: Third party SDK development random record

[Android Pro] developing first-class Android SDK

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.