com.google.android.gms.awareness.fence.AwarenessFence Java Examples

The following examples show how to use com.google.android.gms.awareness.fence.AwarenessFence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AwarenessMotionUpdatesProvider.java    From PrivacyStreams with Apache License 2.0 6 votes vote down vote up
protected void registerFence(final String fenceKey, final AwarenessFence fence) {
    Awareness.FenceApi.updateFences(
            client,
            new FenceUpdateRequest.Builder()
                    .addFence(fenceKey, fence, myPendingIntent)             //Add fence to the pendingIntent
                    .build())
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.e(fenceKey, "Fence was successfully registered.");
                    } else {
                        Log.e(fenceKey, "Fence could not be registered: " + status);
                    }
                }
            });
}
 
Example #2
Source File: StorableLocationFence.java    From JCVD with MIT License 6 votes vote down vote up
@Override
AwarenessFence getAwarenessFence(Context ctx) {
    if (ActivityCompat.checkSelfPermission(ctx,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        switch (mTransitionType) {
            case ENTER_TYPE:
                return LocationFence.entering(mLatitude, mLongitude, mRadius);
            case EXIT_TYPE:
                return LocationFence.exiting(mLatitude, mLongitude, mRadius);
            case IN_TYPE:
                return LocationFence.in(mLatitude, mLongitude, mRadius, mDwellTimeMillis);
        }
    }

    return null;
}
 
Example #3
Source File: GapiFenceManager.java    From JCVD with MIT License 6 votes vote down vote up
/**
 * Add a fence to the Google API
 * If not connected, this will only trigger a connection.
 * This call requires that the following granted permissions:
 *      - ACCESS_FINE_LOCATION if one of the fence is a {@link StorableLocationFence}
 *      - ACTIVITY_RECOGNITION if one of the fence is a {@link StorableActivityFence}
 * @param id the unique id of the fence.
 * @param fence the fence to store
 * @param pendingIntentClassName the class name of the pending intent to call when the fence will be valid.
 * @param status the status that will be called when the addition fails or succeed.
 * @return true if add has been asked, false otherwise.
 */
boolean addFence(@NonNull String id, @NonNull AwarenessFence fence,
                        @NonNull String pendingIntentClassName, @Nullable final ResultCallback<Status> status) {

    FenceUpdateRequest.Builder requestBuilder = new FenceUpdateRequest.Builder()
            .addFence(id, fence, createRequestPendingIntent(pendingIntentClassName));

    mFenceClient.updateFences(requestBuilder.build())
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (status != null) {
                        if (task.isSuccessful()) {
                            status.onResult(Status.RESULT_SUCCESS);
                        } else {
                            status.onResult(Status.RESULT_INTERNAL_ERROR);
                        }
                    }
                }
            });
    return true;
}
 
Example #4
Source File: StorableHeadphoneFence.java    From JCVD with MIT License 5 votes vote down vote up
@Override
AwarenessFence getAwarenessFence(Context ctx) {
    switch (mTriggerType) {
        case STATE:
            return HeadphoneFence.during(mHeadphoneState);
        case PLUGGING_IN:
            return HeadphoneFence.pluggingIn();
        case UNPLUGGING:
            return HeadphoneFence.unplugging();
    }
    return null;
}
 
Example #5
Source File: StorableActivityFence.java    From JCVD with MIT License 5 votes vote down vote up
@RequiresPermission("com.google.android.gms.permission.ACTIVITY_RECOGNITION")
@Override
AwarenessFence getAwarenessFence(Context ctx) {
    switch (mTransitionType) {
        case DURING_TYPE:
            return DetectedActivityFence.during(mActivityTypes);
        case START_TYPE:
            return DetectedActivityFence.starting(mActivityTypes);
        case STOP_TYPE:
            return DetectedActivityFence.stopping(mActivityTypes);
    }
    return null;
}
 
Example #6
Source File: StorableTimeFence.java    From JCVD with MIT License 5 votes vote down vote up
@Override
AwarenessFence getAwarenessFence(Context ctx) {
    switch (mTimingType) {
        case ABSOLUTE:
            return TimeFence.inInterval(mStartTime, mStopTime);
        case DAILY:
            return TimeFence.inDailyInterval(mTimeZone, mStartTime, mStopTime);
        case DAY_OF_WEEK:
            return TimeFence.inIntervalOfDay(mDayOfWeek, mTimeZone, mStartTime, mStopTime);
        case TIME_INTERVAL:
            if (ActivityCompat.checkSelfPermission(ctx,
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                return TimeFence.inTimeInterval(mTimeInterval);
            }
            break;
        case TIME_INSTANT:
            return TimeFence.aroundTimeInstant(mTimeInstant, mStartOffset, mStopOffset);
        case MONDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_MONDAY, mTimeZone, mStartTime, mStopTime);
        case TUESDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_TUESDAY, mTimeZone, mStartTime, mStopTime);
        case WEDNESDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_WEDNESDAY, mTimeZone, mStartTime, mStopTime);
        case THURSDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_THURSDAY, mTimeZone, mStartTime, mStopTime);
        case FRIDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_FRIDAY, mTimeZone, mStartTime, mStopTime);
        case SATURDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_SATURDAY, mTimeZone, mStartTime, mStopTime);
        case SUNDAY:
            return TimeFence.inIntervalOfDay(DAY_OF_WEEK_SUNDAY, mTimeZone, mStartTime, mStopTime);

    }
    return null;
}
 
Example #7
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
private void listing15_29_30_31_32() {
  if (ActivityCompat.checkSelfPermission(this,
    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    return;
  }

  int flags = PendingIntent.FLAG_UPDATE_CURRENT;
  Intent intent = new Intent(this, WalkFenceReceiver.class);
  PendingIntent awarenessIntent = PendingIntent.getBroadcast(this, -1,
    intent, flags);

  // Listing 15-29: Creating Awareness Fences
  // Near one of my custom beacons.
  BeaconState.TypeFilter typeFilter
    = BeaconState.TypeFilter.with("com.professionalandroid.apps.beacon", "my_type");

  AwarenessFence beaconFence = BeaconFence.near(typeFilter);

  // While walking.
  AwarenessFence activityFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);

  // Having just plugged in my headphones.
  AwarenessFence headphoneFence = HeadphoneFence.pluggingIn();

  // Within 1km of Google for longer than a minute.
  double lat = 37.4220233;
  double lng = -122.084252;
  double radius = 1000; // meters
  long dwell = 60000; // milliseconds.
  AwarenessFence locationFence = LocationFence.in(lat, lng, radius, dwell);

  // In the morning
  AwarenessFence timeFence = TimeFence.inTimeInterval(TimeFence.TIME_INTERVAL_MORNING);

  // During holidays
  AwarenessFence holidayFence = TimeFence.inTimeInterval(TimeFence.TIME_INTERVAL_HOLIDAY);

  // Listing 15-30: Combining Awareness Fences
  // Trigger when headphones are plugged in and walking in the morning
  // either within a kilometer of Google or near one of my beacons --
  // but not on a holiday.
  AwarenessFence morningWalk = AwarenessFence
                                 .and(activityFence,
                                   headphoneFence,
                                   timeFence,
                                   AwarenessFence.or(locationFence,
                                     beaconFence),
                                   AwarenessFence.not(holidayFence));

  // Listing 15-31: Creating an Awareness Fence Update Request
  FenceUpdateRequest fenceUpdateRequest
    = new FenceUpdateRequest.Builder()
        .addFence(WalkFenceReceiver.WALK_FENCE_KEY, morningWalk, awarenessIntent)
        .build();

  // Listing 15-32: Adding a new Awareness Fence
  Awareness.FenceApi.updateFences(
    mGoogleApiClient, fenceUpdateRequest).setResultCallback(new ResultCallback<Status>() {
    @Override
    public void onResult(@NonNull Status status) {
      if (!status.isSuccess()) {
        Log.d(TAG, "Fence could not be registered: " + status);
      }
    }
  });
}
 
Example #8
Source File: MainActivity.java    From android-play-awareness with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up {@link AwarenessFence}'s for the sample app, and registers callbacks for them
 * with a custom {@link BroadcastReceiver}
 */
private void setupFences() {
    // DetectedActivityFence will fire when it detects the user performing the specified
    // activity.  In this case it's walking.
    AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);

    // There are lots of cases where it's handy for the device to know if headphones have been
    // plugged in or unplugged.  For instance, if a music app detected your headphones fell out
    // when you were in a library, it'd be pretty considerate of the app to pause itself before
    // the user got in trouble.
    AwarenessFence headphoneFence = HeadphoneFence.during(HeadphoneState.PLUGGED_IN);

    // Combines multiple fences into a compound fence.  While the first two fences trigger
    // individually, this fence will only trigger its callback when all of its member fences
    // hit a true state.
    AwarenessFence walkingWithHeadphones = AwarenessFence.and(walkingFence, headphoneFence);

    // We can even nest compound fences.  Using both "and" and "or" compound fences, this
    // compound fence will determine when the user has headphones in and is engaging in at least
    // one form of exercise.
    // The below breaks down to "(headphones plugged in) AND (walking OR running OR bicycling)"
    AwarenessFence exercisingWithHeadphonesFence = AwarenessFence.and(
            headphoneFence,
            AwarenessFence.or(
                    walkingFence,
                    DetectedActivityFence.during(DetectedActivityFence.RUNNING),
                    DetectedActivityFence.during(DetectedActivityFence.ON_BICYCLE)));


    // Now that we have an interesting, complex condition, register the fence to receive
    // callbacks.

    // Register the fence to receive callbacks.
    Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()
            .addFence(FENCE_KEY, exercisingWithHeadphonesFence, mPendingIntent)
            .build())
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.i(TAG, "Fence was successfully registered.");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Fence could not be registered: " + e);
                }
            });
}
 
Example #9
Source File: StorableFenceManagerTest.java    From JCVD with MIT License 4 votes vote down vote up
@Override
boolean addFence(@NonNull String id, @NonNull AwarenessFence fence, @NonNull String pendingIntentClassName, ResultCallback<Status> status) {
    addResultDict.put(id, status);
    return true;
}
 
Example #10
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 4 votes vote down vote up
private void createFence() {
    checkLocationPermission();

    AwarenessFence activityFence = DetectedActivityFence.during(DetectedActivityFence.STILL);
    AwarenessFence homeFence = LocationFence.in(39.92, -105.7, 100000, 1000 );

    AwarenessFence sittingAtHomeFence = AwarenessFence.and(homeFence, activityFence);

    Intent intent = new Intent(ACTION_FENCE);
    PendingIntent fencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    mFenceBroadcastReceiver = new FenceBroadcastReceiver();
    registerReceiver(mFenceBroadcastReceiver, new IntentFilter(ACTION_FENCE));

    FenceUpdateRequest.Builder builder = new FenceUpdateRequest.Builder();
    builder.addFence(KEY_SITTING_AT_HOME, sittingAtHomeFence, fencePendingIntent);

    Awareness.FenceApi.updateFences( mGoogleApiClient, builder.build() );
}