Android 使用Fence API获取用户活动的更改
示例
如果要检测用户何时开始或完成活动(例如步行,跑步或该DetectedActivityFence课程的其他任何活动),则可以为要检测的活动创建围栏,并在用户开始/结束时得到通知这项活动。通过使用BroadcastReceiver,您将获得Intent包含活动的数据:
//您自己的动作过滤器,如清单中使用的过滤器。 private static final String FENCE_RECEIVER_ACTION =BuildConfig.APPLICATION_ID+ "FENCE_RECEIVER_ACTION"; private static final String FENCE_KEY = "walkingFenceKey"; private FenceReceiver mFenceReceiver; private PendingIntent mPendingIntent; //确保按照“备注”部分所述初始化客户端。 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //等等 //0是标准的活动请求代码,可以根据需要进行更改。 mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(FENCE_RECEIVER_ACTION), 0); registerReceiver(mFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION)); //创建围栏。 AwarenessFence fence = DetectedActivityFence.during(DetectedActivityFence.WALKING); //注册篱笆以接收回调。 Awareness.FenceApi.updateFences(client, new FenceUpdateRequest.Builder() .addFence(FENCE_KEY, fence, mPendingIntent) .build()) .setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { if (status.isSuccess()) { Log.i(FENCE_KEY, "成功注册。"); } else { Log.e(FENCE_KEY, "无法注册: " + status); } } }); } }
现在,BroadcastReceiver当用户更改活动时,您可以收到带有的意图以获取回调:
public class FenceReceiver extends BroadcastReceiver { private static final String TAG = "FenceReceiver"; @Override public void onReceive(Context context, Intent intent) { //获取围栏状态 FenceState fenceState = FenceState.extract(intent); switch (fenceState.getCurrentState()) { case FenceState.TRUE: Log.i(TAG, "User is walking"); break; case FenceState.FALSE: Log.i(TAG, "User is not walking"); break; case FenceState.UNKNOWN: Log.i(TAG, "User is doing something unknown"); break; } } }