In depth exploration of annotations in Android

This article is a summary of GDG Android meetup sharing content

Annotation is a technology we often contact. Java has annotations and Android also has annotations. This paper will try to introduce the annotations in Android and some working principles of annotation based libraries such as butterknife and Otto

In summary, annotations in Android have the following benefits

preparation

By default, the annotation package in Android is not included in the framework. It is a separate package. Usually, we need to introduce this package

However, if we have introduced appcompat, there is no need to refer to support annotations again, because appcompat contains references to it by default

Alternative enumeration

In the earliest days, when we wanted to do some effects worthy of limiting the implementation enumeration, it was usually

However, there are still some imperfections in the above

SetColor (color_red) has the same effect as SetColor (0), which is not readable, but works normally

The SetColor method can accept values other than enumeration, such as SetColor (3). In this case, the program may have problems

A relatively better solution is to use enum in Java The effect of using enumeration is as follows

However, enum is not the best. Compared with the constant in scheme 1, enum occupies a lot of memory and has been listed as not recommended by Google. Therefore, Google has specially introduced some relevant annotations to replace enumeration

The notes of alternative enumeration newly introduced in Android include intdef and stringdef. Here, intdef is taken as an example

Null related annotation

There are two annotations related to null

@Nullable annotated elements can be null @ nonnull annotated elements cannot be null

The above two can modify the following elements

Return value of member property method parameter method

Nonnull detection takes effect

When explicitly passing in null, it is judged that the parameter is null before calling the method

Interval range annotation

Intrange and floatrange in Android are two annotations used to limit the range,

If we pass in an illegal value, as shown below

setCurrentProgress(11);

You'll get such a mistake

Value must be >=0.0 and <= 1.0(was 11)

Length and array size limits

Limit the length of the string

private void setKey(@Size(6) String key) { }

Limit the size of the array collection

Limit the length of a special array, such as a multiple of 3

private void setItemData(@Size(multiple = 3) String[] data) { }

Permission related

In Android, there are many scenarios that require permission, whether dynamic permission management before or after marshmallow It needs to be declared in the manifest. If you forget it, the program will crash Fortunately, an annotation can help us avoid this problem Use the requirespermission annotation

Resource annotation

In Android, almost all resources can have corresponding resource IDs. For example, to obtain the defined string, we can use the following methods

Using this method, we can easily get the defined string, but this writing method also has risks

getStringById(R.mipmap.ic_launcher)

If we unknowingly or negligently pass in such a value, there will be a problem However, if we modify the parameters with resource - related annotations, we can largely avoid errors

In Android, resource annotations are as follows

Color value qualification

Colorres is mentioned in the above section to limit the color resource ID. here we will use colorint, an annotation to limit the color value In earlier textview, SetTextColor was implemented in this way

However, this often happens when the above method is called

myTextView. setTextColor(R.color.colorAccent);

As mentioned above, if you pass the resource ID with the parameter color in the past, the problem of color fetching error will occur. This problem is still serious in the past Fortunately, colorint appeared and changed this problem

When we pass in the color resource value again, we will get an error prompt

CheckResult

This is an annotation about the returned result, which is used to annotate the method. If a method gets the result but does not use the result, there will be an error. Once this error occurs, it means that you have not used the method correctly.

Thread related

Android provides four thread related annotations

Some examples

Note that no error message will appear in this case

Although updateviews will be executed in a new worker thread, there is no error prompt when compiling

Because its judgment basis is that if the thread annotation of updateview (here @ uitthread) and run (without thread annotation) are inconsistent, an error will be prompted If the run method has no thread annotation, it will not be prompted

CallSuper

The overridden method must call the super method

Using this annotation, we can force the method to call the method of the parent class when overriding, such as oncreate and onconfigurationchanged of application

Keep

In the process of compiling and generating APK for Android, we usually need to set minifyenabled to true to achieve the following two effects

Obfuscated code

Delete useless code

However, for some purposes, we need not to confuse some code or delete some code. In addition to configuring complex Proguard files, we can also use @ keep annotation

ButterKnife

Butterknife is an efficient tool for binding views, resources and callbacks By Jake Wharton Butterknife benefits

An example from GitHub

How butterknife works

Take the use of bindview annotation as an example, and the example code is

1. When compiling, the program will automatically generate two classes according to the annotation, here is mainactivity_ ViewBinder. Class and mainactivity_ ViewBinding. class

2. When we call butterknife bind(this); The viewbinder class corresponding to the current class will be found and the bind method will be called. Here, mainactivity will be called_ ViewBinder. Bind method

3.MainActiivty_ ViewBinder. The bind method actually calls findviewbyid, and then performs type conversion and assigns it to the mytextview property of mainactivity

Butterknife's bind method

Gettviewbinder and findviewbinderforclass of butterknife

MainActivity_ Decompile source code of viewbinder

Finder source code

Otto

How Otto works

The following is an analysis of how Otto uses annotations

Register source code

Handlerfinder source code

Specific search implementation

The above is a summary of annotations in Android. Some of the contents of this article refer to support annotations, hoping to help you have a basic understanding of annotations and apply them to practical daily development.

Through this article, I hope to help you thoroughly understand the Android annotation mechanism. Thank you for your support for this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>