Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Android annotation support (Support Annotations)     - Oracle 11.2.0.3 and MySQL5.6 DDL comparison (Database)

- Linux tar compressed exclude a folder (Linux)

- Based on Google Cloud Storage Mirroring open Maven Central Repository (Server)

- Security: Unix operating system intrusion tracking Strikes Back (Linux)

- Install Oracle JDK 8 and JVM class loading mechanism in Linux (Linux)

- Cacti Linux-based system monitoring and alarm (Linux)

- Fedora 22 users to install the VLC media player (Linux)

- Port Telnet command to detect the remote host is turned on (Linux)

- CentOS6 installed Tomcat (Server)

- Java to achieve local fileCopy (Programming)

- 64 Ubuntu 15.04 Linux kernel upgrade to Linux 4.1.0 (Linux)

- Disk storage structure and file recovery experiment (FAT file system) (Linux)

- Internal class broadcasting needs public and static (Programming)

- Chrome plug-in management, online-offline installation, part of the plug presentations (Linux)

- MBR partitions under Linux (Linux)

- Limit the use of the request being Nginx Flood attack (Linux)

- The best tools and techniques to find data on a Unix system (Linux)

- C # socket udp broadcast (Programming)

- Phoenix agents use P2P WebRTC development (Programming)

- The maximum subsequence algorithm and optimization problems (Programming)

 
         
  Android annotation support (Support Annotations)
     
  Add Date : 2017-08-31      
         
         
         
  Annotation support (Support Annotations)

Android support library from version 19.1 introduced a new annotation library, which contains many useful meta-annotation, which you can modify your code to help you find the bug. Support library itself also uses these notes, so as a user of the support library, Android Studio has been based on these notes and check your code label where potential problems. Support library 22.2 version has added 13 new annotations for use.

Use annotations library

Notes The default is not included; they are packaged into a separate library. (Support library now consists of some of the smaller libraries consisting of: v4-support, appcompat, gridlayout, mediarouter etc.)

(If you are using appcompat library, then you can already use these annotations, because appcomat itself also depends on it.)

Add annotations using the easiest way is to open Project Structure dialog box. First on the left is selected module, and then on the right select the Dependencies tab, click the + button at the bottom of the panel, select Library Dependency, assuming you've installed on your Android Support Repository's SDK, then annotation library will appear in the list, you can simply click to select it (this is a first in the list):

Click OK to complete the Project Structure edits. This modifies your build.gradle file, of course, you can also manually edit it:

dependencies {
    compile 'com.android.support:support-annotations:22.2.0'
}
Android application for Android library and two types of module (or you apply com.android.application com.android.library plug), you need to do are already done. If you only want to use these annotations in Java module, then you clearly SDK contains the warehouse, because the support libraries can not be obtained from jcenter (Android Gradle plugin will automatically contain these dependencies, but the Java plug-in does not.)

repositories {
   jcenter ()
   maven {url ' / extras / android / m2repository'}
}
Executive Notes

When you use Android Studio and IntelliJ time, if these labels to annotation method to pass the wrong type of parameters, then the IDE will be marked in real time.

From the Gradle plugins 1.3.0-beta1 release, and installed under the platform Android M Preview tool case, by calling the command line gradle of lint tasks you can perform these checks. If you want to mark as part of the ongoing integration of the problem, so this approach is very useful. Note: This does not include nullness comment. Other notes described in this article can be performed by checking lint.

Nullness Annotations

@Nullable Annotation can be used to mark the given parameter or return value can be null.
Similar, @ NonNull annotation can be used to mark the given parameter or return value can not be null.

If a local variable is null (such as premature because the code checks whether it is null), and you took it passed to a method as a parameter, and the parameter of the method has been marked @NonNull, then the IDE will remind you, you have a potential crash.

v4 support library in FragmentActivity sample code:

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
...

/ **
 * Add support for inflating the & lt; fragment> tag.
 * /
@Nullable
@Override
public View onCreateView (String name, @NonNull Context context, @NonNull AttributeSet attrs) {
...
(If you run Analyze> Infer Nullity, or you type the @NonNull replaced @NotNull, then IDE IntelliJ might offer additional comments. Bottom reference "IntelliJ Annotations" paragraph for more)

Note @NonNull and @Nullable not antagonistic: There is a third possibility: Not specified. When you do not specify @NonNull @Nullable or when the tool can not be determined, so the API will not work.

Initially, we marked on findViewById method @Nullable, technically, that's right: findViewById can return null. But if you know what you are doing (if you give him a pass existed id) that he will not return to the null. When we use @Nullable annotation it, appear bright warning means that the source code editor will be a lot of code. It should clearly be null check if you have realized that each time you use this method, you can only use @Nullable marked the return value. There is a rule of thumb: Look at existing "good code" (such as the review of the product code) to see how the API is being used. If the code is null findings, you should be annotated method @Nullable.

Resource type annotations

Android resource values are usually transmitted using integers. This means that to obtain a drawable parameters used, it can easily be passed to obtain a string method; because they are of type int, the compiler is difficult to distinguish.

Resource type annotation type checking can be provided in this case. For example, a type parameter is @StringRes int eh admitted, if not R.string pass a reference type will be labeled IDE:

In ActionBar example:

import android.support.annotation.StringRes;
...
public abstract void setTitle (@StringRes int resId);
There are many different types of resource Note: Every Android resource types as follows:
@StringRes, @DrawableRes, @ColorRes, @InterpolatorRes, And so on. Under normal circumstances, if there is a resource of type foo, then it's appropriate resource type annotation is FooRes.

In addition, there is a special resource type annotations @AnyRes named. It is used to mark a particular type of resource unknown, but it must be a resource type. For example, in the frame, it is used in Resources # getResourceName (@AnyRes int resId), the use of the time, you can do getResources (). GetResourceName (R.drawable.icon) used to be getResources (). GetResourceName (R .string.app_name) so used, but not so getResources (). getResourceName (42) with.

Please note that if your API supports multiple resource types, you can use multiple annotations to mark your preferences.

IntDef / StringDef: annotation type definition

In addition to integer as a resource reference it can outside, can also be used as the "enumeration" types.

@IntDef And "typedef" is very similar to the role, you can create another annotation, and then specify a list of constant values that you expect to use @IntDef integer, and finally you can use the annotation defined decorate your API up.

An example appcompat library:

import android.support.annotation.IntDef;
...
public abstract class ActionBar {
...
@IntDef ({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
@Retention (RetentionPolicy.SOURCE)
public @interface NavigationMode {}

public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;

@NavigationMode
public abstract int getNavigationMode ();

public abstract void setNavigationMode (@NavigationMode int mode);
The above is part of the non-annotated existing API. We have created a new comment (NavigationMode) and marked it with @IntDef, we specify a constant value by @IntDef available for the return value or parameter. We've also added @Retention (RetentionPolicy.SOURCE) tells the compiler that this newly defined annotation need not be recorded in the resulting .class file (Translator's Note: When the source code level, the generated class file annotation was compiled automatically removed).

After using this annotation, if you pass a parameter or return value is not specified constant values, then, IDE will be marked out of this situation.

You can also specify an integer type is a marker of nature; so the client code by |, & and other operators while delivering a plurality of constants:

@IntDef (Flag = true, value = {
        DISPLAY_USE_LOGO,
        DISPLAY_SHOW_HOME,
        DISPLAY_HOME_AS_UP,
        DISPLAY_SHOW_TITLE,
        DISPLAY_SHOW_CUSTOM
})
@Retention (RetentionPolicy.SOURCE)
public @interface DisplayOptions {}
Finally, there is a string version of the notes is @StringDef, and role @IntDef it is essentially the same, except that it is for the string. The comments generally not used, but sometimes very useful, for example, in defining the parameters of the Activity # getSystemService method to pass the time.

For more detailed information on the type annotations, see
https://developer.android.com/tools/debugging/annotations.html#enum-annotations

Thread Notes: @UiThread, @WorkerThread, ...

(Support library 22.2 and later versions support.)

If your method can only be called in the specified thread types, then you can use the following four annotation to label it:

@UiThread
@MainThread
@WorkerThread
@BinderThread
If a class all methods have the same thread demand, then you can annotate the class itself. For example android.view.View, was marked by @UiThread.

A good example on the use of thread annotation is AsyncTask:

@WorkerThread
protected abstract Result doInBackground (Params ... params);

@MainThread
protected void onProgressUpdate (Progress ... values) {
}
If you try to call any method or methods onProgressUpdate View in doInBackground overridden methods where, IDE tools will immediately mark it as an error:

@UiThread Or @MainThread?

In the process, only one main thread. This is @MainThread. At the same time this is also a thread @UiThread. For example, the main window activity would run on this thread. However, it also has the ability to create additional threads for the application. This is rare, generally have such features are system processes. Usually the life cycle and associated with @MainThread tagging, and View hierarchy associated with @UiThread marked. But because it is essentially a @UiThread @MainThread, and in most cases is a @MainThread @UiThread, so tools (lint, Android Studio, etc.) can put them interchangeable, so you can call in a @MainThread the method can also place calls @UiThread method, and vice versa.

Integer RGB color

When your API expect a color resource you can use @ColorRes label, but when you have a contrary usage scenario, this usage is not available, because you do not expect a color resource id, but a real the RGB or ARGB color value.

In this case, you can use @ColorInt annotations, that you are a representative of a desired color integer value:

public void setTextColor (@ColorInt int color)
With this, when you pass a color id instead of the color values of the time, lint will mark this incorrect code:

Value constraints: @Size, @IntRange, @FloatRange

If your argument is a float or double type, and must be within a certain range, you can use @FloatRange annotation:

public void setAlpha (@FloatRange (from = 0.0, to = 1.0) float alpha) {
If someone is when to use the API to pass a value from 0 to 255, for example, try to call setAlpha (128), then the tool will capture this problem:

Similarly, if your argument is an int or long type, you can use the annotation constraint @IntRange its value within a specific range:

public void setAlpha (@IntRange (from = 0, to = 255) int alpha) {...}
These notes apply to the parameters is very useful, because the user is likely to provide an error range of parameters, such as setAlpha example above, is to use some API 0-255 way, and in some cases the use of float value 0-1 way.

Finally, for data collection and string, you can use @Size annotation parameters to define the size of the collection (the time when the parameter is a string, you can define the length of the string).

A few examples

Collection can not be empty: @Size (min = 1)
The maximum string can have only 23 characters: @Size (max = 23)
Arrays can only have two elements: @Size (2)
The size of the array must be a multiple of 2 (such as graphics API to obtain the position x / y coordinate arrays: @Size (multiple = 2)

Permissions Notes: @RequiresPermission

If you call your method requires callers have specific permissions, you can use @RequiresPermission annotation:

@RequiresPermission (Manifest.permission.SET_WALLPAPER)
public abstract void setWallpaper (Bitmap bitmap) throws IOException;
If you need at least one set of permissions, you can use anyOf properties:

@RequiresPermission (AnyOf = {
    Manifest.permission.ACCESS_COARSE_LOCATION,
    Manifest.permission.ACCESS_FINE_LOCATION})
public abstract Location getLastKnownLocation (String provider);
If you also need multiple permissions, you can use allOf properties:

@RequiresPermission (AllOf = {
    Manifest.permission.READ_HISTORY_BOOKMARKS,
    Manifest.permission.WRITE_HISTORY_BOOKMARKS})
public static final void updateVisitedHistory (ContentResolver cr, String url, boolean real) {
For permission intents and permission requirements can mark directly on the intent of the definition of constant string field (they usually have been marked @SdkConstant annotated over):

@RequiresPermission (Android.Manifest.permission.BLUETOOTH)
public static final String ACTION_REQUEST_DISCOVERABLE =
        "Android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
For permission to content providers, you may need to separate read and write access to the label, it can be used to annotate each @Read or @Write permission requirements:

@ RequiresPermission.Read (@RequiresPermission (READ_HISTORY_BOOKMARKS))
@ RequiresPermission.Write (@RequiresPermission (WRITE_HISTORY_BOOKMARKS))
public static final Uri BOOKMARKS_URI = Uri.parse ( "content: // browser / bookmarks");

Method overrides: @CallSuper

If your API allows the user to rewrite your way, but then, you need to turn your own way (parent method) when overwriting is also called, this time you can use @CallSuper mark:

@CallSuper
protected void onCreate (@Nullable Bundle savedInstanceState) {
With this later, when overridden method does not call the parent method, the tool will give marks tips:

(Android Studio lint checks 1.3 Preview 1 There is an annotation about this bug, the bug is, even for the rewrite will be given, this bug in Preview 2 has been modified version, you can update to version Preview 2 by canary channel.)

Return Value: @CheckResult

If your method returns a value, you expect the caller to do something with this value, then you can use this method @CheckResult annotation label.

You do not need to micro every non-empty methods are labeled. Its main purpose is to help which can be confusing, difficult to understand the API users.

For example, many developers may have to String.trim () scanty that calls this method, you can make changes to remove the blank character string. If this method is @CheckResult marked, the tool will issue a warning to those who the caller does not use trim () returns the result.

Android in, Context # checkPermission this method has been @CheckResult marked:

@ (Suggest = "# enforcePermission (String, int, int, String)")
public abstract int checkPermission (@NonNull String permission, int pid, int uid);
This is very important because some developers use context.checkPermission think they have implemented a privilege - but in fact, this method only just checked a success and the feedback value only. If developers use this method, but it does not return a value, then the developer may really want to call the Context # enforcePermission method instead checkPermission.

@VisibleForTesting

You can put this on the label annotation class, method, or field, so you can use them at the time of testing.

@Keep

We also comment Curry added @Keep notes, but also supports plug-in Gradle (although already in progress). Classes and methods to be marked in this comment will not be confused when confused.

Use annotations in your own library

If you use these annotations in your own library, and is constructed to generate aar package through Gradle, so when building the Android Gradle plugin will extract annotation information on AAR file for your client reference library use. In the AAR file you can see a file called annotations.zip, and this is documented annotation information using IntelliJ extended annotations XML format. This is necessary because the .class file does not contain enough to deal with more than @IntDef annotation information; we just need to pay attention to the constant reference to a record, not its value. Execute it only if and when your project rely annotation library, Android Gradle plugin will extract annotation tasks as part of the build. (Note: only source is placed in the reserved Note .aar file; class level will be placed in classes.jar.)

IntelliJ comment

IntelliJ, Android Studio is based on its development, IntelliJ its own set of annotations; IntDef analysis actually is code reuse MagicConstant analysis, IntelliJ null analysis actually used was a set of configured null annotations. If you run Analyze> Infer Nullity ..., it will try to find all the null constraints and add them. This check is sometimes inserted IntelliJ comment. You can search, replace Android annotation library annotations, or you can directly use IntelliJ comment. In build.gradle or can be added in the following dependency through Dependencies dialog panel Project Structure:

dependencies {
    compile 'com.intellij: annotations: 12.0'
}
     
         
         
         
  More:      
 
- C ++ overloaded stream insertion operator and the stream extraction operator (Programming)
- Use libcurl library download url image (Programming)
- Generated characters using Java Videos (Programming)
- Java collections series (Programming)
- Usage of sudo (Linux)
- Revive Adserver ad server installation on Ubuntu 15.04 / CentOS7 (Server)
- Arduino UNO simulation development environment set up and run simulation (Linux)
- 4 lvcreate example commonly used commands (Linux)
- C ++ Const breaking rules (Programming)
- Detailed iptables (Linux)
- OpenStack Folsom create an instance of the failure of the Quota Fixed_IP articles (Server)
- Erlang concurrency and foundation (Programming)
- Install VMware Tools in Debian (Linux)
- Elasticsearch 2.20 Highlight (Server)
- Network Security Basics Linux command (Linux)
- Linux FTP setting file description (Server)
- The Linux disguised as windows to make the system more secure (Linux)
- Distributed Hadoop1.2.1 cluster installation (Server)
- C ++ thread creates transmission parameters are changed (Programming)
- Redis performance test (Database)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.