Detailed explanation of the use of Support Annotation Library

Overview

Support Annotation Library is a new function package introduced in Android Support Library 19.1, which contains many useful meta-annotations. Used to help developers find possible bugs during compilation. The Support Library itself also uses the annotations provided by the Annotations Library to improve the code quality of the Library.
Every version of Android is constantly improving the Annotation Library. In the Android Support Library 22.2 version, 13 new Annotation Library annotations have been added. The Android Support Library has grown to 25, and there are already multiple independent jars, such as our common Support-v4, Support-v7...

Use of Annotation Library

If our sdk has Android Support Respository installed, then we can open the Srrucure of the project, select Module, select the Dependencies tab, click the Add button, and select Android Library. Then these annotations can be easily added to our project through gradle.

compile 'com.android.support:support-annotations:23.1.1'

Common Notes

Nullness annotation

Parameters decorated with the @NonNull annotation cannot be null. In the following code example, we have a name variable with a value of null, which is passed as a parameter to the sayHello function, which requires this parameter to be a non-null String type:

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String name = null;
        sayHello(name);
    }

    void sayHello(@NonNull String s) {
        Toast.makeText(this, "Hello " + s, Toast.LENGTH_LONG).show();
    }
}

Since the parameter String s in the code are decorated with @NonNull annotation, the IDE will remind us that there is a problem in this place in the form of a warning.
write picture description here

Resource Type Annotations

We know that in Android, resources are usually represented as integers and stored in R.java, which means that if the resource is passed in String type, the compilation will report an error. In order to give developers a hint, Android has a resource type Annotations, in the latest version, each resource corresponds to an annotation.
write picture description here
Common resource annotations are as follows:
AnimRes
AnimatorRes
AnyRes
ArrayRes
AttrRes
BoolRes
ColorRes
DimenRes
DrawableRes
FractionRes
IdRes
IntegerRes
InterpolatorRes
LayoutRes
MenuRes
PluralsRes
RawRes
StringRes
StyleRes
StyleableRes
TransitionRes
XmlRes

type definition annotation

In Android development, integers are not only used to represent resource reference values, but also enumerations. The IntDef annotation is a new annotation used to define integers, which we can use to mark our own apis, for example:

public class IceCreamFlavourManager {
    private int flavour;
    public static final int VANILLA = 0;
    public static final int CHOCOLATE = 1;
    public static final int STRAWBERRY = 2;
    @IntDef({VANILLA, CHOCOLATE, STRAWBERRY})
    public @interface Flavour {
    }
    @Flavour
    public int getFlavour() {
        return flavour;
    }
    public void setFlavour(@Flavour int flavour) {
        this.flavour = flavour;
    }
}

At this time, if we call IceCreamFlavourManager.setFlavour with the wrong integer value, the IDE will report an error.
write picture description here
Of course, we can also specify integer values ​​as flags, that is to say, these integer values ​​can use '|' or '&' to perform and or operations. If we define @Flavour as the following flag.

@IntDef(flag = true, value = {VANILLA, CHOCOLATE, STRAWBERRY})

    public @interface Flavour {

}

Then we can call it like this.

iceCreamFlavourManager.setFlavour(IceCreamFlavourManager.VANILLA & IceCreamFlavourManager
                .CHOCOLATE);

The usage of @StringDef is basically the same as @IntDef.

Permission annotation

In Android, there are many scenarios that require the use of permissions, whether it is dynamic permission management before or after Marshmallow. It needs to be declared in the manifest. If you forget it, it will cause the program to crash. Fortunately, there is an annotation to help us avoid This problem. Use the RequiresPermission annotation.

@RequiresPermission(Manifest.permission.SET_WALLPAPER)
  public void changeWallpaper(Bitmap bitmap) throws IOException {
}

Color value limit annotation

The above section mentioned ColorRes, which is used to define the color resource id, here we will use ColorInt, an annotation used to define the value of Color. In the earlier TextView's setTextColor was implemented like this.

public void setTextColor(int color) {
  mTextColor = ColorStateList.valueOf(color);
  updateTextColors();
}

thread annotation

Many threads are often involved in Android development, such as main thread, child thread and other operations. I believe that you are using EventBus, message bus... I have seen more, and Android provides four thread-related annotations.

  • @UiThread, usually equivalent to the main thread, the annotation method needs to be executed in UIThread, such as the View class uses this annotation
  • @MainThread main thread, the first thread created after frequent startup
  • @WorkerThread Worker threads are generally background threads, such as doInBackground in AsyncTask.
  • The @BinderThread annotation method must be executed in the BinderThread thread, which is generally used less.
    For example, the famous AsyncTask.
new AsyncTask<Void, Void, Void>() {
    //doInBackground is already annotated with @WorkerThread
    @Override
    protected Void doInBackground(Void... params) {
      return null;
      updateViews();//error
    }
  };

@UiThread
public void updateViews() {
  Log.i(LOGTAG, "updateViews ThreadInfo=" + Thread.currentThread());
}

Note that no error message will appear in this case.

new Thread(){
  @Override
  public void run() {
    super.run();
    updateViews();
  }
}.start();

Although updateViews will be executed in a new worker thread, there is no error message at compile time. Because its judgment is based on the fact that if the thread annotation of updateView (here @UiThread) and run (no thread annotation) are inconsistent, an error will be prompted. If the run method has no thread annotation, it will not prompt.

CallSuper rewrite function annotation

The overridden method must call the super method. Using this annotation, we can force methods to call parent class methods such as ApplicationonCreate, onConfigurationChanged, etc. when overriding.

@Keep annotation

In the process of compiling and generating APK in Android, we usually need to set minifyEnabled to true to achieve the following two effects:
obfuscate code and
delete useless code.
In addition to configuring complex Proguard files, we can also use the @Keep annotation.

@Keep
public static int getBitmapWidth(Bitmap bitmap) {
  return bitmap.getWidth();
}

return value annotation

When we are developing, sometimes we need to do something about the returned value, so the @CheckResult annotation has been used for a long time. If a method gets the result but does not use the result, an error will occur. Once such an error occurs, it will be It means that you are not using this method correctly.

@CheckResult
public String trim(String s) {
  return s.trim();
}

Annotations can be seen everywhere in Android development, such as ButterKnife, afinal, eventbus, etc., which greatly improve our development efficiency.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325742614&siteId=291194637