【Android】高低API版本兼容之@TargetApi与@SuppressLint("NewApi")

一、使用@TargetApi annotaion, 使高版本API的代码在低版本SDK不报错

例如:

AsyncTask.THREAD_POOL_EXECUTOR, 这个静态变量是API11才有的, 设置project build target 为 2.1.

这个时候eclipse会提示找不到这个变量。


只要在方法前面加一个 @TargetApi(11), 这样就不会报错了,程序已经可以跑在低版本SDK上了。

另外在代码上要加一个版本判断是否执行该代码, 例子如下


@TargetApi(11)

public void text(){

if(Build.VERSION.SDK_INT >= 11){

             // 使用api11 新加 api

        }

}


问题:我在4.0以上的版本用这个view.setAlpha(1),现在在低版本2.3上用,加了@TargetApi(11)一样报错?
答:Indicates that Lint should treat this type as targeting a given API level, no matter what the project target is.
TargetApi是让Line检查编译通过的作用,具体使用还需要使用if else 判断版本


二、What is better: @SuppressLint or @TargetApi?

@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.

For example, suppose that, instead of blocking the StrictMode complaints about your networking bug, you were trying to work around the issue of AsyncTask being serialized on newer versions of Android. You have a method like this in your code to opt into the thread pool on newer devices and use the default multithread behavior on older devices:

  @TargetApi(11)
  static public <T> void executeAsyncTask(AsyncTask<T, ?, ?> task,
                                          T... params) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    }
    else {
      task.execute(params);
    }
  }

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.


转自:http://blog.csdn.net/s278777851/article/details/8903739
http://stackoverflow.com/questions/14341042/what-is-better-suppresslint-or-targetapi

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值