在广播接收器中删除或取消注册围栏

时间:2016-11-16 02:05:07

标签: android google-awareness

我正在使用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实例。我怎样才能在接收器中获得该实例?

P.s:我无法在onStop上调用remove cz即使活动被破坏也可以触发围栏。

2 个答案:

答案 0 :(得分:0)

试试此代码

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

        context.unregisterReceiver(mReceiver);
    }

};

注册:

this.registerReceiver(this.mReceiver, new IntentFilter(...));

答案 1 :(得分:0)

您可以通过添加具有唯一键的围栏来删除执行/完成的围栏,以便每个围栏具有不同的围栏键。现在要删除它,只需调用removeFence函数,并使用唯一键来移除栅栏。

样本函数如下:

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();
        }
    });
}