开始使用

本文档介绍了如何开始在 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:19.1.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: