@TargetApi and @SuppressLint have
the same core effect: they suppress the Lint error.
The difference is that with @TargetApi,
you declare, via the parameter, what API level you have addressed in your code, so that the error can pop up again if you later modify the method to try referencing something newer than the API level cited in @TargetApi.
Having @TargetApi(11) means
that if Lint detects that I am using something newer than my android:minSdkVersion,
but up to API Level 11, Lint will not complain. In this case, that works. If, however, I modified this method to reference something that wasn't added until API Level 14, then the Lint error would appear again, because my @TargetApi(11) annotation
says that I only fixed the code to work on API Level 11 and below, not API Level 14 and below.
Using @SuppressLint('NewApi'),
I would lose the Lint error for any API level, regardless of what my code references and what my code is set up to handle.
Hence, @TargetApi is
the preferred annotation, as it allows you to tell the build tools "OK, I fixed this category of problems" in a more fine-grained fashion.
本文深入解析了@TargetApi和@SuppressLint在Android开发中的核心作用,阐述了它们在抑制Lint错误上的相同效果,重点讨论了@TargetApi如何通过指定API级别来精确控制代码兼容性,以及@SuppressLint在任何API级别的应用中消除所有Lint警告的特性。文章通过实例解释了使用@TargetApi进行更精细化问题修复的优势,并对比了两者的实际应用场景。
6889

被折叠的 条评论
为什么被折叠?



