開始使用

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

如要使用 Awareness API,你必須擁有 Google 帳戶。如果您已經擁有帳戶,則一切已準備就緒。您可能也想要建立另一個獨立的 Google 帳戶來進行測試。

事前準備

取得 API 金鑰

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

設定應用程式

  1. 在專案層級 build.gradle 檔案中,將 Google 的 Maven 存放區加進 buildscriptallprojects 區段:

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

    dependencies {
      implementation 'com.google.android.gms:play-services-awareness:19.0.1'
    }
    
  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() 的範例,說明如何透過 Aware 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: