开始使用

本文档介绍了如何在 Android 上开始使用 Awareness API 进行开发。Awareness API 是 Google Play 服务 的一部分。

如需使用 Awareness API,您需要一个 Google 账号。 如果您已经具有账号,则您已准备就绪。为了进行测试,您可能还需要一个单独的 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: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 文件中。所需权限因应用使用的方法和围栏类型而异。

调用示例

以下对 getDetectedActivity() 的调用示例展示了如何将无连接 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: