Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發環境

Android Studio(七):用註解強化程式碼檢測

編輯:Android 開發環境

像 Lint 這類程式碼檢測工具能幫你揪出問題、提升品質,但在某些情境下它其實力有未逮。以 Android 的資源 ID 為例,無論是字串、圖片、顏色還是其他資源類型,背後都用一個 int 來表示,檢測工具根本無法分辨這到底是哪一種資源。這種情況下,即便有檢測工具把關,你的應用仍可能在執行時渲染失敗甚至無法啟動。

註解(Annotation)的作用,就是替 Lint 這類工具提供額外提示,協助它偵測更深層的問題,例如空指標異常或資源類型衝突。

Android 支援多種註解,可套用於方法、參數與返回值,例如:

1、@Nullable:允許為空;

2、@NonNull:不可為空;

3、@StringRes:提示 Lint 這是 String 資源;

4、@DrawableRes:提示為 Drawable 資源;

5、@ColorRes:提示為 Color 資源;

6、@InterpolatorRes:提示為 Interpolator 資源;

7、@AnyRes:提示為任一類型的資源;

8、@UiThread:應在主執行緒中呼叫。

以上僅是部分常見註解。

加入基本註解

要在程式碼中使用註解,得先加上對應的相依項:

1、開啟 File > Project Structure;

2、選取相應模組,切到 Dependencies 分頁;

3、點擊 + 匯入一個 Library dependency;

4、在 Choose Library Dependency 視窗中選擇 support-annotations,按下 OK。

此時 build.gradle 會自動更新 support-annotations 相依項,當然你也可以手動加入:

dependencies {

compile 'com.android.support:support-annotations:23.3.0'

}

若你在 Library 中加入註解並打包成 AAR,這些註解會以 XML 格式保存在 annotations.zip 裡。

加入空值註解

用 @Nullable 與 @NonNull 來標示變數、參數或返回值是否可為空。例如,當一個值為 null 的區域變數被傳給標註了 @NonNull 的參數時,編譯就會產生警告:

import android.support.annotation.NonNull;

@NonNull

@Override

public View onCreateView(String name, @NonNull Context context,

@NonNull AttributeSet attrs) {

...

}

空值分析

Android Studio 會執行空值分析,並自動為程式碼補上相關註解,可用來檢測:

1、方法呼叫是否可能返回 null;

2、方法是否保證不返回 null;

3、變數是否不可為 null;

4、變數是否不可長期持有 null 值。

加入資源註解

例如加上 @StringRes,就能檢測某個資源參數是否確實來自 R.string。檢測時若沒有傳入 R.string,便會產生警告:

import android.support.annotation.StringRes;

public abstract void setTitle(@StringRes int resId);

加入執行緒註解

執行緒註解用來驗證某方法是否執行在特定執行緒,支援的有:

1、@UiThread;2、@MainThread;3、@WorkerThread;4、@BinderThread。

其中 @UiThread 與 @MainThread 可以互換使用。

加入數值約束註解

透過 @IntRange、@FloatRange 與 @Size 來驗證傳入參數的值。

@IntRange 用於檢查整數是否落在指定區間,以下確保 alpha 介於 0 到 255:

public void setAlpha(@IntRange(from=0,to=255) int alpha) { ... }

@FloatRange 則檢查浮點數範圍,以下確保 alpha 介於 0.0 到 1.0:

public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {...}

@Size 用來驗證集合、陣列或字串的大小,例如 @Size(min=1) 可判斷集合非空,@Size(2) 可驗證陣列恰有兩個元素。以下確保 location 陣列至少含一個元素:

int[] location = new int[3];

button.getLocationOnScreen(@Size(min=1) location);

加入權限註解

用 @RequiresPermission 驗證呼叫方法時所需的權限。若只需具備多個權限其中之一,用 anyOf;若需同時具備多個,則用 allOf:

@RequiresPermission(Manifest.permission.SET_WALLPAPER)

public abstract void setWallpaper(Bitmap bitmap) throws IOException;

另一個例子:

@RequiresPermission(allOf = {

Manifest.permission.READ_EXTERNAL_STORAGE,

Manifest.permission.WRITE_EXTERNAL_STORAGE})

public static final void copyFile(String dest, String source) {

...

}

加入結果檢測註解

用 @CheckResults 驗證方法的結果或返回值是否被使用:

@CheckResult(suggest="#enforcePermission(String,int,int,String)")

public abstract int checkPermission(@NonNull String permission, int pid, int uid);

加入呼叫父類註解

用 @CallSuper 驗證覆寫方法時是否確實呼叫了父類的實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved