Google Awareness API
请记住, Snapshot API 用于请求当前状态,而 Fence API 会持续检查指定状态,并在应用程序未运行时发送回调。
总的来说,使用 Snapshot API 或 Fence API 有几个基本步骤:
-
从 Google Developers Console 获取 API 密钥
-
向清单添加必要的权限和 API 密钥:
<!-- Not required for getting current headphone state --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!-- Only required for actvity recognition --> <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/> <!-- Replace with your actual API key from console --> <meta-data android:name="com.google.android.awareness.API_KEY" android:value="YOUR_API_KEY"/> <!-- Required for Snapshot API only --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY"/>
-
初始化
GoogleApiClient
,最好是在你的活动的onCreate()
方法中。GoogleApiClient client = new GoogleApiClient.Builder(context) .addApi(Awareness.API) .build(); client.connect();
-
调用你选择的 API
-
解析结果
检查所需用户权限的简单方法是这样的方法:
private boolean isFineLocationGranted() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(getClass().getSimpleName(), "Fine location permission not granted!");
}
}