【Android】高低APIバージョン対応@TargetApiと@SuppressLint("NewApi")

13102 ワード

一、@TargetApi annotaionを使用して、高バージョンAPIのコードを低バージョンSDKでエラーを報告しない
例:
AsyncTask.THREAD_POOL_EXECUTORは、この静的変数がAPI 11ならではであり、プロジェクトビルドターゲットを2.1とする.
このときeclipseはこの変数が見つからないことを示します.
メソッドの前に@TargetApi(11)を追加すれば、エラーは発生せず、プログラムはすでに低バージョンSDKに走ることができます.
また、コードにバージョンを付けて、そのコードを実行するかどうかを判断します.例は以下の通りです.
@TargetApi(11)
public void text(){
if(Build.VERSION.SDK_INT >= 11){
//api 11で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