开始使用

本文档介绍了如何在 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() 的示例调用演示了如何将无连接 Google Play 服务模型与 Awareness API 搭配使用:

    // 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: