Awareness API значительно задерживает обратные вызовы активности

Я создал класс и BroadcastReceiver, чтобы получать обратные вызовы от API осведомленности, когда ходьба или бег заканчиваются. Я не получал своевременных обратных вызовов и сначала подумал, что это из-за того, что я зарегистрировал «остановку» обратного вызова, но затем, после того, как я немного отложил телефон, я получил несколько обратных вызовов! Но это было далеко не тогда, когда я перестал ходить. Не менее чем через 5 минут после остановки. Иногда я не получаю обратных вызовов, даже когда приложение Google Fit записывает активность.

Так как я получил обратные вызовы по крайней мере несколько раз, я знаю, что регистрация в порядке. Почему звонки задерживаются и иногда отсутствуют?

Для справки: я регистрирую эти обратные вызовы в onStart основного действия, т. е. в это время вызывается InitialAwareness внутри onstart действия. И я никогда не отменяю их регистрацию. Я не собираюсь использовать его таким образом в производстве, это было просто для тестирования. Плюс моя первоначальная попытка зарегистрировать заборы в контексте приложения не удалась.

Вот вспомогательный класс, который я сделал для настройки регистрации клиента Google и заборов.

public class AwarenessHelper {


public static final String WALKING_ENDED_FENCE = "walkingEndedKey";
public static final String RUNNING_ENDED_FENCE = "runningEndedKey";
public static final String TYPE
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;
    }
}
WALKING = "duringWalkingKey"; public static final String TYPE
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;
    }
}
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
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;
    }
}
WALKING, DetectedActivityFence.during(DetectedActivityFence.WALKING), getBroadcastPendingIntent(context)) .addFence(TYPE
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;
    }
}
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; } }

Вот BroadcastReceiver:

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

Я получаю уведомления, но с большой задержкой, а иногда и вовсе нет. Я запускаю действие много раз, поэтому, возможно, заборы регистрируются снова и снова? Это релевантный факт? Также подходит ли контекст службы или широковещательного приемника для инициализации клиентов осведомленности и барьеров?


person user6877096    schedule 06.01.2017    source источник
comment
Вы нашли решение для этого?   -  person Dibzmania    schedule 25.09.2017


Ответы (1)


Awareness подписывается на получение ActivityRecognition обновлений довольно редко, поэтому нет ничего неожиданного в том, что вы получите ответ через несколько минут.

Вы также должны беспокоиться о том, что у вас слишком много заборов без отмены регистрации в целом.

Также нет причин иметь отдельный pendingIntent для каждого из ваших заборов; вы можете иметь один pendingIntent и добавить все заборы к нему. Используйте дополнительный ключ забора, чтобы различать результаты каждого забора. И снова делайте unregister, когда это имеет смысл. В противном случае заборы могут зависнуть даже после того, как ваше приложение исчезнет.

person androidFunk    schedule 08.02.2017