关于android的@TargetApi和@SuppressLint("NewApi")
2017-09-16 17:10
567 查看
转载自:http://www.cnblogs.com/Barcelona/p/4142666.html
看别人的代码好多地方用到了@TargetApi。以前一直不知道这个是什么意思。后面偶然看了下sdk。才有所明白。
其实这个东西就是在你使用了android Lint检查工具的时候,为了防止代码出现提示性错误而设计的。说白了,如果你关闭了android Lint,那么这个对你屁用都没有。
比如你的androidmanifest设置了minsdkversion为8,那么你在代码中使用了高于api8的代码,
就算你用的是4.4的sdk进行的代码编译,只要你没使用@TargetApi,很抱歉,运行android lint直接就显示错误提示。这个时候我们该怎么办呢?就是在方法或类的开头写上@TargetApi(xx)。如果你下面的代码要在api13的情况下运行,那么xx处你就填写13。不能填低了,填低了,还是报错。
这和@SuppressLint("NewApi")不一样。suppress只告诉lint,我这代码如果高于你的minsdkversion,那么请忽略编译错误。
最后强调一点:targetapi和你代码的运行环境没任何关系。意思就是说即使你写了@TargetApi(11)。不代表你的这个 方法就会被限制在android 3.0的设备上运行。
因此兼容性判断还是必不可少的。所以@targetapi最常用的情景代码如下:
看别人的代码好多地方用到了@TargetApi。以前一直不知道这个是什么意思。后面偶然看了下sdk。才有所明白。
其实这个东西就是在你使用了android Lint检查工具的时候,为了防止代码出现提示性错误而设计的。说白了,如果你关闭了android Lint,那么这个对你屁用都没有。
比如你的androidmanifest设置了minsdkversion为8,那么你在代码中使用了高于api8的代码,
就算你用的是4.4的sdk进行的代码编译,只要你没使用@TargetApi,很抱歉,运行android lint直接就显示错误提示。这个时候我们该怎么办呢?就是在方法或类的开头写上@TargetApi(xx)。如果你下面的代码要在api13的情况下运行,那么xx处你就填写13。不能填低了,填低了,还是报错。
这和@SuppressLint("NewApi")不一样。suppress只告诉lint,我这代码如果高于你的minsdkversion,那么请忽略编译错误。
最后强调一点:targetapi和你代码的运行环境没任何关系。意思就是说即使你写了@TargetApi(11)。不代表你的这个 方法就会被限制在android 3.0的设备上运行。
因此兼容性判断还是必不可少的。所以@targetapi最常用的情景代码如下:
@TargetApi(11) public void reqFragmentManger(){ if(Build.Version.SDK_INIT >= Build.VersionCodes.HONEYCOMB) { FragmentManager manager = getFragmentManager(); } }
相关文章推荐
- android 基础 @SuppressLint("NewApi")和@TargetApi()的作用与区别
- 我的Android进阶之旅------>Android中高低API版本兼容使用@TargetApi或者@SuppressLint("NewApi")
- 【Android】高低API版本兼容之@TargetApi与@SuppressLint("NewApi")
- Android @SuppressLint("NewApi")和@TargetApi()的区别
- Android中Build类以及@SuppressLint("NewApi")和@TargetApi()区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- (转)在低版本的SDK里使用高版本函数@SuppressLint("NewApi") or @TargetApi?
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别章标题
- @SuppressLint("NewApi")和@TargetApi(number)使用比较
- @SuppressLint("NewApi")和@TargetApi()的区别
- @TargetApi() 与@SuppressLint("NewApi")
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别