本文档介绍了如何在 Android 上开始使用 Awareness API 进行开发。Awareness API 是 Google Play 服务的一部分。
如需使用 Awareness API,您需要拥有一个 Google 账号。如果您已经有账号,则无需进行任何操作。为了进行测试,您可能还需要一个单独的 Google 账号。
准备工作
获取 API 密钥
如果您尚未启用 Awareness API 并获取 Google API 密钥,请按照注册和 API 密钥中的步骤进行操作。
配置您的应用
- 在您的项目级 - build.gradle文件中,同时在- buildscript和- allprojects两个部分中添加 Google 的 Maven 代码库:- buildscript { repositories { google() } } allprojects { repositories { google() } }
- 将 Awareness API 的依赖项添加到模块的应用级 Gradle 文件(通常为 - app/build.gradle)中:- dependencies { implementation 'com.google.android.gms:play-services-awareness:19.1.0' }
- 将 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> 
- 向应用的 - 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: