android中@TargetApi的作用是什么?

网上有很多的解释,前篇一律,都是说可以让低版本编译代码,然后高版本就能兼容代码了。

这是很荒谬的。然而我还是做了验证。结果是这种说法是完全错误的。


请看google官方的文档对@TargetApi的描述。

由于google被墙,只能用这个链接:

http://gate.baidu.com/?src=http%3A%2F%2Ftools.android.com%2Frecent%2Flintapicheck


请看这几句的翻译:



As you can see, lint now has a database of the full Android API such that it knows precisely which version each API call was introduced in. If it detects that you are attempting to call a method which is not available in all versions you are trying to support, it will warn you with messages like the above.

正如你所看到的, lint现 在有完整的Android API的一个数据库,这样它清楚地知道哪个版本的哪一个API调用了。如果它检测到你正试图调用一个方法不是在所有版本都可用,那么它将提醒给你上面的消息。

 

Of course, if you're building your project with the same version of Android as your oldest support version, the compiler will complain if it finds an API call it can't resolve. However, that approach has some downsides. In particular, you may want to access newer APIs on platforms where they are available. If you're compiling against the oldest version of the platform, you would need to use reflection to access all the new APIs, which can be really cumbersome, especially if you have a lot of code using the newer APIs.
The way most developers get around this is to actually use a newer build target, which means you can access all the new APIs directly. You then add some code checks to make sure that the code path which calls the newer APIs is only reached when running on a version which supports it.

当然,如果您编译的项目的版本和支持的最低支持的版本相同, 编译器会提示找不到相关API。然而,这种方法有一些缺点。特别是,您可能希望访问新的平台上可用的api。如果你对老版本的编译平台,您将需要使用反射来访问所有的新api,可真的麻烦,特别是如果你有很多的代码使用新的api。


实际上大多数开发人员解决这个问题的方法是使用更高的版本来编译这个项目,这意味着您可以直接访问所有的新api。然后添加一些代码检查,以确保调用的代码路径上运行时达成的新api只是一个版本支持它。

 

 

However, when you do this you run the risk of accidentally calling newer APIs, and that's what Lint now helps you detect.
What about code where you are deliberately calling newer APIs from a class you know will only be loaded in the right circumstances? In that case you can "mark" the code as targeting a newer version of the API. Simply annotate the code with the new @TargetApiannotation:

然而,当你这么做了,那么在低版本上调用新的api可能会有崩溃的风险, 这就是lint检测提示的作用之所在。



那么如何保证你调用的新的api的代码的相关类只会在合适的版本下才加载? 在这种情况下你可以“标注”目标的代码的所在版本的API。简单的注释代码@TargetApi(11)

 

If the whole class is targeting newer APIs, you can place the annotation on the class instead:

如果整个类都是新的api的版本,你就可以把@Target标注移除掉。

 

综上,@Target的作用在于提示:使用高编译版本的代码,为了通用性兼容运行此代码的低版本平台。要求程序员做出区分对待的加载。如用内部类等方式区分加载。