開始使用

本文說明如何開始在 Android 上使用 Awareness API 進行開發。Awareness API 是 Google Play 服務的一部分。

您必須擁有 Google 帳戶,才能使用 Awareness API。如果您已擁有帳戶,就可以開始使用了。您可能也需要一個專用於測試的 Google 帳戶。

事前準備

取得 API 金鑰

如果您尚未啟用 Awareness API 並取得 Google API 金鑰,請按照「註冊和 API 金鑰」中的步驟操作。

設定應用程式

  1. 在專案層級的 build.gradle 檔案中,請同時在 buildscriptallprojects 區段中納入 Google 的 Maven 存放區:

    buildscript {
        repositories {
            google()
        }
    }
    
    allprojects {
        repositories {
            google()
        }
    }
    
  2. 將 Awareness API 的依附元件新增至模組的應用程式層級 Gradle 檔案,通常為 app/build.gradle

    dependencies {
      implementation 'com.google.android.gms:play-services-awareness:19.1.0'
    }
    
  3. 將 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>
  4. 在應用程式的 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: