@TargetApi() 与@SuppressLint("NewApi")
来源:互联网 发布:冷热数据分离 编辑:程序博客网 时间:2024/05/21 11:35
一、@TargetApi()
1、安卓开发中,在低版本SDK使用高版本的API会报错:
解决方法:
(1):换一种实现方法(一般处理方法);
(2):在高版本SDK中使用高版本API,低版本SDK中使用效果可能会差点的折衷方案。
方法(2)可以用如下技巧来实现:
(1):在使用了高版本API的方法前面加一个 @TargetApi(API号)
(2):在代码上用版本判断来控制不同版本使用不同的代码
@TargetApi(11) public void text(){ if(Build.VERSION.SDK_INT >= 11){ // 使用api11 新加api的方法 } else { // 低版本的折衷处理方法 } }
二、@SuppressLint(“NewApi”)与@TargetApi()的区别
1、在Android代码中,我们有时会使用比我们在AndroidManifest中设置的android:minSdkVersion版本更高的方法,此时编译器会提示警告,解决方法是在方法上加上@SuppressLint(“NewApi”)或者@TargetApi()。
2、区别:
(1) @SuppressLint(“NewApi”)屏蔽一切新api中才能使用的方法报的android lint错误
(2) @TargetApi() 只屏蔽某一新api中才能使用的方法报的android lint错误
3、例子:
某个方法中使用了api9新加入的方法,而项目设置的android:minSdkVersion=8,此时在方法上加@SuppressLint(“NewApi”)和@TargetApi(Build.VERSION_CODES.GINGERBREAD)都可以,以上是通用的情况。
而当你在此方法中又引用了一个api11才加入的方法时,@TargetApi(Build.VERSION_CODES.GINGERBREAD)注解的方法又报错了,而@SuppressLint(“NewApi”)不会报错,这就是区别。
当然,不管你使用了哪个注解,作用仅仅是屏蔽android lint错误,所以在方法中还要判断版本做不同的操作。
TargetApi和你代码的运行环境没任何关系。意思就是说即使你写了@TargetApi(11),不代表你的这个 方法就会被限制在android 3.0的设备上运行。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { // } else {// Pre GINGERBREAD // }
1、其实这个东西就是在你使用了Android Lint检查工具的时候,为了防止代码出现提示性错误而设计的。说白了,如果你关闭了android Lint,那么这个对你屁用都没有。
2、@SuppressLint(“NewApi”)只告诉Lint,我这代码如果高于你的android:minSdkVersion,那么请忽略编译错误。
参考文献:
@TargetAPI + 版本判断实现高低API版本兼容
@SuppressLint(“NewApi”)和@TargetApi()的区别
关于android的@TargetApi和@SuppressLint(“NewApi”)
- @TargetApi() 与@SuppressLint("NewApi")
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- @SuppressLint("NewApi")和@TargetApi()的区别
- 设计模式之工厂方法模式和抽象工厂模式
- git仓储使用
- Nginx几种常见实现301重定向方法上的区别
- 28.Oracle杂记——Oracle常用动态视图v$rollstat
- CSS实现播放暂停按钮样式
- @TargetApi() 与@SuppressLint("NewApi")
- java编程思想 第四章 练习4
- 文档总结13-linux中yum与定时任务
- 线性代数的一些笔记(仅供自己作back up)
- PHP之Redis的常用操作
- 游戏开发中的数学和物理算法:定义线
- Going deeper with convolutions
- jzoj5424【NOIP2017提高A组集训10.25】凤凰院凶真
- C# checkBox控件CheckedChanged与CheckedStateChanged区别