使用 Fence API 更改使用者活動
如果要檢測使用者何時開始或完成諸如步行,執行或 DetectedActivityFence
類的任何其他活動之類的活動,你可以為要檢測的活動建立圍欄 ,並在使用者啟動時收到通知/完成這項活動。通過使用 BroadcastReceiver
,你將獲得包含活動的資料的 Intent
:
// Your own action filter, like the ones used in the Manifest.
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;
// Make sure to initialize your client as described in the Remarks section.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// etc.
// The 0 is a standard Activity request code that can be changed to your needs.
mPendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(FENCE_RECEIVER_ACTION), 0);
registerReceiver(mFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));
// Create the fence.
AwarenessFence fence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
// Register the fence to receive callbacks.
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, "Successfully registered.");
} else {
Log.e(FENCE_KEY, "Could not be registered: " + status);
}
}
});
}
}
現在,你可以通過 BroadcastReceiver
接收意圖,以便在使用者更改活動時獲得回撥:
public class FenceReceiver extends BroadcastReceiver {
private static final String TAG = "FenceReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// Get the fence state
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;
}
}
}