【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

你可能感兴趣的:(android)