1

我创建了一个类和一个 BroadcastReceiver 来从感知 api 获取回调,以便在步行或跑步结束时进行。我没有得到及时的回拨,起初以为是因为我注册了一个“停止”回拨,但是在将手机放下一段时间后,我确实收到了几个回拨!但这离我停止走路的时间还很远。停止后至少 5 分钟。有时即使 Google Fit 应用程序记录活动,我也不会收到回调。

因为我至少收到过几次回电,所以我知道注册没问题。为什么电话会延迟,有时甚至会丢失?

作为背景参考,我在主活动的 onStart 中注册了这些回调,即那时在活动的 onstart 中调用了initialAwareness。而且我从不注销它们。我不打算在生产中以这种方式使用它,它只是为了测试。另外,我最初尝试使用应用程序上下文注册栅栏失败了。

这是我为设置谷歌客户端和围栏的注册而制作的助手类。

public class AwarenessHelper {


public static final String WALKING_ENDED_FENCE = "walkingEndedKey";
public static final String RUNNING_ENDED_FENCE = "runningEndedKey";
public static final String TYPE_2_WALKING = "duringWalkingKey";
public static final String TYPE_2_RUNNING = "duringRunningKey";

private String tag = AwarenessHelper.class.getSimpleName();

public void initiateAwareness(final Activity context)
{
    final GoogleApiClient googleApiClient = buildClient(context);
    Log.d(tag, "Initiating blocking connect");
    googleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            if ( googleApiClient.isConnected() )
            {
                Log.d(tag, "Client connected, initiating awareness fence registration");
                registerAwarenessFences(context, googleApiClient);
            }
            else
            {
                Log.d(tag, "Couldn't connect");
            }

        }

        @Override
        public void onConnectionSuspended(int i) {

        }


    });

    googleApiClient.connect();
}

private void registerAwarenessFences(Context context, GoogleApiClient mGoogleApiClient) {
    Awareness.FenceApi.updateFences(
            mGoogleApiClient,
            new FenceUpdateRequest.Builder()
                    .addFence(WALKING_ENDED_FENCE, DetectedActivityFence.stopping(DetectedActivityFence.WALKING), getBroadcastPendingIntent(context))
                    .addFence(RUNNING_ENDED_FENCE, DetectedActivityFence.stopping(DetectedActivityFence.RUNNING), getBroadcastPendingIntent(context))
                    .addFence(TYPE_2_WALKING, DetectedActivityFence.during(DetectedActivityFence.WALKING), getBroadcastPendingIntent(context))
                    .addFence(TYPE_2_RUNNING, DetectedActivityFence.stopping(DetectedActivityFence.RUNNING), getBroadcastPendingIntent(context))
                    .build())
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.i(tag, "Fence was successfully registered.");
                    } else {
                        Log.e(tag, "Fence could not be registered: " + status);
                    }
                }
            });
}

private GoogleApiClient buildClient(final Activity activity)
{
    GoogleApiClient client = new GoogleApiClient.Builder(activity)
            .addApi(Awareness.API)
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    if ( connectionResult.hasResolution() && connectionResult.getErrorCode() == CommonStatusCodes.SIGN_IN_REQUIRED )
                    {
                        try {
                            connectionResult.startResolutionForResult(activity, GOOGLE_FIT_AUTHORIZATION_REQUEST_CODE);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                    }
                }
            })
            .build();
    return client;
}

private PendingIntent getBroadcastPendingIntent(Context context)
{
    Intent intent = new Intent(AWARENESS_BROADCAST_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    return pendingIntent;
}
}

这是广播接收器:

public class AwarenessHelper {


    public static final String WALKING_ENDED_FENCE = "walkingEndedKey";
    public static final String RUNNING_ENDED_FENCE = "runningEndedKey";
    public static final String TYPE_2_WALKING = "duringWalkingKey";
    public static final String TYPE_2_RUNNING = "duringRunningKey";

    private String tag = AwarenessHelper.class.getSimpleName();

    public void initiateAwareness(final Activity context)
    {
        final GoogleApiClient googleApiClient = buildClient(context);
        Log.d(tag, "Initiating blocking connect");
        googleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
            @Override
            public void onConnected(@Nullable Bundle bundle) {
                if ( googleApiClient.isConnected() )
                {
                    Log.d(tag, "Client connected, initiating awareness fence registration");
                    registerAwarenessFences(context, googleApiClient);
                }
                else
                {
                    Log.d(tag, "Couldn't connect");
                }

            }

            @Override
            public void onConnectionSuspended(int i) {

            }


        });

        googleApiClient.connect();
    }

    private void registerAwarenessFences(Context context, GoogleApiClient mGoogleApiClient) {
        Awareness.FenceApi.updateFences(
                mGoogleApiClient,
                new FenceUpdateRequest.Builder()
                        .addFence(WALKING_ENDED_FENCE, DetectedActivityFence.stopping(DetectedActivityFence.WALKING), getBroadcastPendingIntent(context))
                        .addFence(RUNNING_ENDED_FENCE, DetectedActivityFence.stopping(DetectedActivityFence.RUNNING), getBroadcastPendingIntent(context))
                        .addFence(TYPE_2_WALKING, DetectedActivityFence.during(DetectedActivityFence.WALKING), getBroadcastPendingIntent(context))
                        .addFence(TYPE_2_RUNNING, DetectedActivityFence.stopping(DetectedActivityFence.RUNNING), getBroadcastPendingIntent(context))
                        .build())
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        if (status.isSuccess()) {
                            Log.i(tag, "Fence was successfully registered.");
                        } else {
                            Log.e(tag, "Fence could not be registered: " + status);
                        }
                    }
                });
    }

    private GoogleApiClient buildClient(final Activity activity)
    {
        GoogleApiClient client = new GoogleApiClient.Builder(activity)
                .addApi(Awareness.API)
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        if ( connectionResult.hasResolution() && connectionResult.getErrorCode() == CommonStatusCodes.SIGN_IN_REQUIRED )
                        {
                            try {
                                connectionResult.startResolutionForResult(activity, GOOGLE_FIT_AUTHORIZATION_REQUEST_CODE);
                            } catch (IntentSender.SendIntentException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                })
                .build();
        return client;
    }

    private PendingIntent getBroadcastPendingIntent(Context context)
    {
        Intent intent = new Intent(AWARENESS_BROADCAST_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        return pendingIntent;
    }
}

我收到了通知,但经过大量延迟,有时根本没有。我多次启动活动,所以也许围栏正在一遍又一遍地注册?这是一个相关的事实吗?服务或广播接收器上下文是否也适用于意识客户端和栅栏的初始化?

4

1 回答 1

0

Awareness订阅以获取ActivityRecognition更新的频率很低,因此几分钟后您会收到回复也就不足为奇了。

您还应该担心在没有取消注册的情况下有太多的栅栏。

此外,没有理由pendingIntent为每个栅栏单独设置;你可以有一个单一的pendingIntent并添加所有的栅栏反对那个。额外使用栅栏键来区分每个栅栏的结果。再一次,unregister在有意义的时候做。否则,即使您的应用程序消失,栅栏也可能会出现。

于 2017-02-08T06:21:55.410 回答