本文說明如何在 Android 上開始使用 Awareness API 進行開發。Awareness API 是 Google Play 服務的一部分。
如要使用 Awareness API,您需要 Google 帳戶。 如果你已有帳戶,就可以開始使用了。您可能也需要專門用於測試的 Google 帳戶。
事前準備
取得 API 金鑰
如果您尚未啟用 Awareness API 並取得 Google API 金鑰,請按照「註冊和 API 金鑰」一節的步驟操作。
設定應用程式
在專案層級的
build.gradle檔案中,同時在buildscript和allprojects區段中加入 Google 的 Maven 存放區:buildscript { repositories { google() } } allprojects { repositories { google() } }將 Awareness API 的依附元件新增至模組的應用程式層級 Gradle 檔案,通常為
app/build.gradle:dependencies { implementation 'com.google.android.gms:play-services-awareness:19.1.0' }將 Awareness API 金鑰加進應用程式的
AndroidManifest.xml檔案。方法是新增含android:name="com.google.android.awareness.API_KEY"的<meta-data>代碼。在android:value中插入您的 Awareness API 金鑰,並以半形引號括住。<manifest> <application> <meta-data android:name="com.google.android.awareness.API_KEY" android:value="API_KEY"/> </application> </manifest>
在應用程式的
AndroidManifest.xml檔案中新增必要權限。視應用程式使用的 API 方法和柵欄類型而定,所需權限會有所不同。
呼叫範例
以下範例呼叫 getDetectedActivity(),說明如何搭配 Awareness API 使用無連線的 Google Play 服務模型:
// Each type of contextual information in the snapshot API has a corresponding "get" method.
// For instance, this is how to get the user's current Activity.
Awareness.getSnapshotClient(this).getDetectedActivity()
.addOnSuccessListener(new OnSuccessListener<DetectedActivityResponse>() {
@Override
public void onSuccess(DetectedActivityResponse dar) {
ActivityRecognitionResult arr = dar.getActivityRecognitionResult();
// getMostProbableActivity() is good enough for basic Activity detection.
// To work within a threshold of confidence,
// use ActivityRecognitionResult.getProbableActivities() to get a list of
// potential current activities, and check the confidence of each one.
DetectedActivity probableActivity = arr.getMostProbableActivity();
int confidence = probableActivity.getConfidence();
String activityStr = probableActivity.toString();
mLogFragment.getLogView().println("Activity: " + activityStr
+ ", Confidence: " + confidence + "/100");
}
})
後續步驟
進一步瞭解 Awareness API 中的不同 API: