1

我正在使用 Awareness API 并创建了这样的围栏:

AwarenessFence activityFence = DetectedActivityFence.during(DetectedActivityFence.STILL);
AwarenessFence headphoneFence = HeadphoneFence.during(HeadphoneState.PLUGGED_IN);

AwarenessFence stillWithHeadPhoneFence = AwarenessFence.and(activityFence, headphoneFence);

Intent intent = new Intent(Constants.ACTION_FENCE);
                        PendingIntent fencePendingIntent = PendingIntent.getBroadcast(((Activity) context), 0, intent, 0);

MyFenceReceiver mFenceBroadcastReceiver = new MyFenceReceiver();
                        ((Activity) context).registerReceiver(mFenceBroadcastReceiver, new IntentFilter(Constants.ACTION_FENCE));

FenceUpdateRequest.Builder builder = new FenceUpdateRequest.Builder();
                        builder.addFence(Constants.IDLE_WITH_HEADPHONES_ON, stillWithHeadPhoneFence, fencePendingIntent);

Awareness.FenceApi.updateFences(googleApiClient, builder.build());

这是我的广播接收器:

public void onReceive(Context context, Intent intent) {
        if(TextUtils.equals(Constants.ACTION_FENCE, intent.getAction())) {
            FenceState fenceState = FenceState.extract(intent);

            if( TextUtils.equals(Constants.IDLE_WITH_HEADPHONES_ON, fenceState.getFenceKey() ) ) {

                if( fenceState.getCurrentState() == FenceState.TRUE ) {
                    //
                }
            }


        }

问题是,一旦接收器第一次执行,我需要取消注册或移除栅栏。我正在寻找移除围栏的方法,它需要一个 GoogleApiClient 实例。我怎样才能在接收器中获取该实例?

Ps:我不能在 onStop 中调用 remove cz 即使活动已被破坏,栅栏也可以被触发。

4

2 回答 2

0

You can remove the fences which are executed/completed by adding fences with unique key, so that each and every fences have different fence key. Now to remove it, just call removeFence function with the unique key for the fence to be removed.

sample function is as given below:

private void unregisterFence(String unique_key) {
    Awareness.FenceApi.updateFences(
            mGoogleApiClient,
            new FenceUpdateRequest.Builder()
                    .removeFence(unique_key)
                    .build()).setResultCallback(new ResultCallbacks<Status>() {
        @Override
        public void onSuccess(@NonNull Status status) {
            Toast.makeText(MainActivity.this,
                    "Fence unregistered successfully.",
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(@NonNull Status status) {
            Toast.makeText(MainActivity.this,
                    "Cannot unregister fence.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}
于 2017-05-24T16:33:19.750 回答
0

试试这个代码

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Code ....

        context.unregisterReceiver(mReceiver);
    }

};

登记 :

this.registerReceiver(this.mReceiver, new IntentFilter(...));
于 2016-11-16T07:32:31.193 回答