開始使用

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

如要使用 Awareness API,您需要 Google 帳戶。 如果您已經有帳戶,則您已準備好了。您可能也想要另外有個測試用的 Google 帳戶。

事前準備

取得 API 金鑰

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

設定應用程式

  1. 在專案層級的 build.gradle 檔案中,同時在 buildscript 和 allprojects 區段中加入 Google 的 Maven 存放區:

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

    dependencies {
      implementation 'com.google.android.gms:play-services-awareness:20.0.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: