TargetApi not taken into account

馋奶兔 提交于 2019-11-30 06:03:18

@TargetApi does not prevent any code from being run, it is merely for annotating code and preventing compiler errors for new APIs once you know you are only conditionally calling them.

You still need to add something along the lines of

if (Build.VERSION.SDK_INT > 7){
    //...
}

With almost one year of more thinking about this, I would like to add a tiny complement to @Guykun 's answer :

The @TargetApi will be only be used by tools to say developers "Hey, don't use this method below XXX android SDK". Typically lint.

So, if you design a method like :

if (Build.VERSION.SDK_INT > 7){
    //...
}

then you should add @TargetApi( 7 ) to your method's signature.

BUT, if you add an else statement, and provide an alternative that makes it work for all versions of Android like :

if (Build.VERSION.SDK_INT > 7){
    //...
} else {
    //...
}

then you should not add @TargetApi( 7 ) to your method's signature. Otherwise, other developers will think they can't use your method belw api level 7, but indeed, it would work for them as well.

So this annotation has to be used, for static analysis, to indicate the minimum api level supported by the method. As in :

@TargetApi( 7 )
public void foo() {
   if (Build.VERSION.SDK_INT > 7){
       //...
   else if (Build.VERSION.SDK_INT > 10){
       //...
   } 
}

and even better, use constants defined in android.Build.VERSION_CODES.*.

BTW, you would have noticed that this is useless for private methods indeed, except to get a cleaner code and help to promote the method public in the future.

To enforce lint error when using a method targeted towards higher Api Level, you can use RequiresApi instead of TargetApi and whenever you'll try to use the method without checking the version code, you'll get compilation error.

This is what the documentation says about RequiresApi

This is similar in purpose to the older @TargetApi annotation, but more clearly expresses that this is a requirement on the caller, rather than being used to "suppress" warnings within the method that exceed the minSdkVersion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!