com.google.android.gms.awareness.Awareness Java Examples
The following examples show how to use
com.google.android.gms.awareness.Awareness.
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: MainActivity.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 6 votes |
private void listing15_28() { // Listing 15-28: Retrieving Snapshot context signal results Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient) .setResultCallback(new ResultCallback<DetectedActivityResult>() { @Override public void onResult(@NonNull DetectedActivityResult detectedActivityResult) { if (!detectedActivityResult.getStatus().isSuccess()) { Log.e(TAG, "Current activity unknown."); } else { ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult(); DetectedActivity probableActivity = ar.getMostProbableActivity(); // TODO: Do something with the detected user activity. } } }); }
Example #2
Source File: SnapshotApiActivity.java From android-samples with Apache License 2.0 | 6 votes |
/** * Check weather the headphones are plugged in or not? This is under snapshot api category. */ private void getHeadphoneStatus() { Awareness.SnapshotApi.getHeadphoneState(mGoogleApiClient) .setResultCallback(new ResultCallback<HeadphoneStateResult>() { @Override public void onResult(@NonNull HeadphoneStateResult headphoneStateResult) { if (!headphoneStateResult.getStatus().isSuccess()) { Toast.makeText(SnapshotApiActivity.this, "Could not get headphone state.", Toast.LENGTH_LONG).show(); return; } HeadphoneState headphoneState = headphoneStateResult.getHeadphoneState(); //display the status TextView headphoneStatusTv = (TextView) findViewById(R.id.headphone_status); headphoneStatusTv.setText(headphoneState.getState() == HeadphoneState.PLUGGED_IN ? "Plugged in." : "Unplugged."); } }); }
Example #3
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 6 votes |
private void detectBeacons() { if( !checkLocationPermission() ) { return; } Awareness.SnapshotApi.getBeaconState(mGoogleApiClient, BEACON_TYPE_FILTERS) .setResultCallback(new ResultCallback<BeaconStateResult>() { @Override public void onResult(@NonNull BeaconStateResult beaconStateResult) { if (!beaconStateResult.getStatus().isSuccess()) { Log.e("Test", "Could not get beacon state."); return; } BeaconState beaconState = beaconStateResult.getBeaconState(); if( beaconState == null ) { Log.e("Tuts+", "beacon state is null"); } else { for(BeaconState.BeaconInfo info : beaconState.getBeaconInfo()) { Log.e("Tuts+", new String(info.getContent())); } } } }); }
Example #4
Source File: SnapshotApiActivity.java From android-samples with Apache License 2.0 | 6 votes |
/** * Get the current weather condition at current location. */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") private void getWeather() { //noinspection MissingPermission Awareness.SnapshotApi.getWeather(mGoogleApiClient) .setResultCallback(new ResultCallback<WeatherResult>() { @Override public void onResult(@NonNull WeatherResult weatherResult) { if (!weatherResult.getStatus().isSuccess()) { Toast.makeText(SnapshotApiActivity.this, "Could not get weather.", Toast.LENGTH_LONG).show(); return; } //parse and display current weather status Weather weather = weatherResult.getWeather(); String weatherReport = "Temperature: " + weather.getTemperature(Weather.CELSIUS) + "\nHumidity: " + weather.getHumidity(); ((TextView) findViewById(R.id.weather_status)).setText(weatherReport); } }); }
Example #5
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 6 votes |
private void detectActivity() { Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient) .setResultCallback(new ResultCallback<DetectedActivityResult>() { @Override public void onResult(@NonNull DetectedActivityResult detectedActivityResult) { ActivityRecognitionResult result = detectedActivityResult.getActivityRecognitionResult(); Log.e("Tuts+", "time: " + result.getTime()); Log.e("Tuts+", "elapsed time: " + result.getElapsedRealtimeMillis()); Log.e("Tuts+", "Most likely activity: " + result.getMostProbableActivity().toString()); for( DetectedActivity activity : result.getProbableActivities() ) { Log.e("Tuts+", "Activity: " + activity.getType() + " Liklihood: " + activity.getConfidence() ); } } }); }
Example #6
Source File: MainActivity.java From android-play-awareness with Apache License 2.0 | 6 votes |
/** * Helper method to retrieve weather data using the Snapshot API. Since Weather is protected * by a runtime permission, this snapshot code is going to be called in multiple places: * {@link #printSnapshot()} when the permission has already been accepted, and * {@link #onRequestPermissionsResult(int, String[], int[])} when the permission is requested * and has been granted. */ private void getWeatherSnapshot() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Awareness.getSnapshotClient(this).getWeather() .addOnSuccessListener(new OnSuccessListener<WeatherResponse>() { @Override public void onSuccess(WeatherResponse weatherResponse) { Weather weather = weatherResponse.getWeather(); weather.getConditions(); mLogFragment.getLogView().println("Weather: " + weather); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG, "Could not get weather: " + e); } }); } }
Example #7
Source File: MainActivity.java From android-play-awareness with Apache License 2.0 | 6 votes |
@Override protected void onPause() { // Unregister the fence: Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder() .removeFence(FENCE_KEY) .build()) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.i(TAG, "Fence was successfully unregistered."); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG, "Fence could not be unregistered: " + e); } }); super.onPause(); }
Example #8
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 6 votes |
private void detectNearbyPlaces() { if( !checkLocationPermission() ) { return; } Awareness.SnapshotApi.getPlaces(mGoogleApiClient) .setResultCallback(new ResultCallback<PlacesResult>() { @Override public void onResult(@NonNull PlacesResult placesResult) { Place place; for( PlaceLikelihood placeLikelihood : placesResult.getPlaceLikelihoods() ) { place = placeLikelihood.getPlace(); Log.e("Tuts+", place.getName().toString() + "\n" + place.getAddress().toString() ); Log.e("Tuts+", "Rating: " + place.getRating() ); Log.e("Tuts+", "Likelihood that the user is here: " + placeLikelihood.getLikelihood() * 100 + "%"); } } }); }
Example #9
Source File: AwarenessMotionUpdatesProvider.java From PrivacyStreams with Apache License 2.0 | 6 votes |
protected void unregisterFence(final String fenceKey) { Awareness.FenceApi.updateFences( client, new FenceUpdateRequest.Builder() .removeFence(fenceKey) .build()).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { if (status.isSuccess()) { Log.e("Fence", "Fence " + fenceKey + " successfully removed."); } else { Log.e("Fence", "Fence " + fenceKey + " can not be removed."); } } }); }
Example #10
Source File: AwarenessMotionUpdatesProvider.java From PrivacyStreams with Apache License 2.0 | 6 votes |
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 #11
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 6 votes |
private void detectWeather() { if( !checkLocationPermission() ) { return; } Awareness.SnapshotApi.getWeather(mGoogleApiClient) .setResultCallback(new ResultCallback<WeatherResult>() { @Override public void onResult(@NonNull WeatherResult weatherResult) { Weather weather = weatherResult.getWeather(); Log.e("Tuts+", "Temp: " + weather.getTemperature(Weather.FAHRENHEIT)); Log.e("Tuts+", "Feels like: " + weather.getFeelsLikeTemperature(Weather.FAHRENHEIT)); Log.e("Tuts+", "Dew point: " + weather.getDewPoint(Weather.FAHRENHEIT)); Log.e("Tuts+", "Humidity: " + weather.getHumidity() ); if( weather.getConditions()[0] == Weather.CONDITION_CLOUDY ) { Log.e("Tuts+", "Looks like there's some clouds out there"); } } }); }
Example #12
Source File: MainActivity.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 6 votes |
private void listing15_34() { // Listing 15-34: Removing an Awareness Fence FenceUpdateRequest fenceUpdateRequest = new FenceUpdateRequest.Builder() .removeFence(WalkFenceReceiver.WALK_FENCE_KEY) .build(); 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 removed: " + status); } } }); }
Example #13
Source File: MainActivity.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Awareness.API) .enableAutoManage(this, // MainActivity this) // OnConnectionFailedListener .build(); int permission = ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION); if (permission != PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST); } }
Example #14
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 5 votes |
private void detectLocation() { if( !checkLocationPermission() ) { return; } Awareness.SnapshotApi.getLocation(mGoogleApiClient) .setResultCallback(new ResultCallback<LocationResult>() { @Override public void onResult(@NonNull LocationResult locationResult) { Location location = locationResult.getLocation(); Log.e("Tuts+", "Latitude: " + location.getLatitude() + ", Longitude: " + location.getLongitude()); Log.e("Tuts+", "Provider: " + location.getProvider() + " time: " + location.getTime()); if( location.hasAccuracy() ) { Log.e("Tuts+", "Accuracy: " + location.getAccuracy()); } if( location.hasAltitude() ) { Log.e("Tuts+", "Altitude: " + location.getAltitude()); } if( location.hasBearing() ) { Log.e("Tuts+", "Bearing: " + location.getBearing()); } if( location.hasSpeed() ) { Log.e("Tuts+", "Speed: " + location.getSpeed()); } } }); }
Example #15
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 5 votes |
private void detectHeadphones() { Awareness.SnapshotApi.getHeadphoneState(mGoogleApiClient) .setResultCallback(new ResultCallback<HeadphoneStateResult>() { @Override public void onResult(@NonNull HeadphoneStateResult headphoneStateResult) { HeadphoneState headphoneState = headphoneStateResult.getHeadphoneState(); if (headphoneState.getState() == HeadphoneState.PLUGGED_IN) { Log.e("Tuts+", "Headphones are plugged in."); } else { Log.e("Tuts+", "Headphones are NOT plugged in."); } } }); }
Example #16
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 5 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); checkLocationPermission(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Awareness.API) .enableAutoManage(this, this) .build(); mGoogleApiClient.connect(); }
Example #17
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 5 votes |
@Override protected void onPause() { Awareness.FenceApi.updateFences( mGoogleApiClient, new FenceUpdateRequest.Builder() .removeFence(KEY_SITTING_AT_HOME) .build()); if (mFenceBroadcastReceiver != null) { unregisterReceiver(mFenceBroadcastReceiver); } super.onPause(); }
Example #18
Source File: HeadphoneFenceApiActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Build the google api client to use awareness apis. */ private void buildApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(HeadphoneFenceApiActivity.this) .addApi(Awareness.API) .addConnectionCallbacks(this) .build(); mGoogleApiClient.connect(); }
Example #19
Source File: ActivityFanceApiDemo.java From android-samples with Apache License 2.0 | 5 votes |
/** * Build the google api client to use awareness apis. */ private void buildApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Awareness.API) .addConnectionCallbacks(this) .build(); mGoogleApiClient.connect(); }
Example #20
Source File: SnapshotApiActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Get user's current location. We are also displaying Google Static map. */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") private void getLocation() { //noinspection MissingPermission Awareness.SnapshotApi.getLocation(mGoogleApiClient) .setResultCallback(new ResultCallback<LocationResult>() { @Override public void onResult(@NonNull LocationResult locationResult) { if (!locationResult.getStatus().isSuccess()) { Toast.makeText(SnapshotApiActivity.this, "Could not get location.", Toast.LENGTH_LONG).show(); return; } //get location Location location = locationResult.getLocation(); ((TextView) findViewById(R.id.current_latlng)).setText(location.getLatitude() + ", " + location.getLongitude()); //display the time TextView timeTv = (TextView) findViewById(R.id.latlng_time); SimpleDateFormat sdf = new SimpleDateFormat("h:mm a dd-MM-yyyy", Locale.getDefault()); timeTv.setText("as on: " + sdf.format(new Date(location.getTime()))); //Load the current map image from Google map String url = "https://maps.googleapis.com/maps/api/staticmap?center=" + location.getLatitude() + "," + location.getLongitude() + "&zoom=20&size=400x250&key=" + getString(R.string.api_key); Picasso.with(SnapshotApiActivity.this).load(url).into((ImageView) findViewById(R.id.current_map)); } }); }
Example #21
Source File: SnapshotApiActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Get the nearby places using Snapshot apis. We are going to display only first 5 places to the user in the list. */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") private void getPlace() { //noinspection MissingPermission Awareness.SnapshotApi.getPlaces(mGoogleApiClient) .setResultCallback(new ResultCallback<PlacesResult>() { @Override public void onResult(@NonNull final PlacesResult placesResult) { if (!placesResult.getStatus().isSuccess()) { Toast.makeText(SnapshotApiActivity.this, "Could not get places.", Toast.LENGTH_LONG).show(); return; } //get the list of all like hood places List<PlaceLikelihood> placeLikelihoodList = placesResult.getPlaceLikelihoods(); // Show the top 5 possible location results. LinearLayout linearLayout = (LinearLayout) findViewById(R.id.current_place_container); linearLayout.removeAllViews(); if (placeLikelihoodList != null) { for (int i = 0; i < 5 && i < placeLikelihoodList.size(); i++) { PlaceLikelihood p = placeLikelihoodList.get(i); //add place row View v = LayoutInflater.from(SnapshotApiActivity.this).inflate(R.layout.row_nearby_place, linearLayout, false); ((TextView) v.findViewById(R.id.place_name)).setText(p.getPlace().getName()); ((TextView) v.findViewById(R.id.place_address)).setText(p.getPlace().getAddress()); linearLayout.addView(v); } } else { Toast.makeText(SnapshotApiActivity.this, "Could not get nearby places.", Toast.LENGTH_LONG).show(); } } }); }
Example #22
Source File: SnapshotApiActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Build the google api client to use awareness apis. */ private void buildApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(SnapshotApiActivity.this) .addApi(Awareness.API) .addConnectionCallbacks(this) .build(); mGoogleApiClient.connect(); }
Example #23
Source File: CombineFenceApiActivity.java From android-samples with Apache License 2.0 | 5 votes |
/** * Build the google api client to use awareness apis. */ private void buildApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(CombineFenceApiActivity.this) .addApi(Awareness.API) .addConnectionCallbacks(this) .build(); mGoogleApiClient.connect(); }
Example #24
Source File: AwarenessImpl.java From Myna with Apache License 2.0 | 5 votes |
@Override public void init(Context context) { client = new GoogleApiClient.Builder(context) .addApi(Awareness.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); client.connect(); HandlerThread googleHandleThread = new HandlerThread("googleHandleThread"); googleHandleThread.start(); googleHandler = new Handler(googleHandleThread.getLooper()){ @Override public void handleMessage(Message msg) { Awareness.SnapshotApi.getDetectedActivity(client) .setResultCallback(new ResultCallback<DetectedActivityResult>(){ @Override public void onResult(@NonNull DetectedActivityResult detectedActivityResult) { handleResult(detectedActivityResult); } }); Message newMsg = new Message(); newMsg.what = 0; googleHandler.sendMessageDelayed(newMsg, 5000); } }; }
Example #25
Source File: AwarenessMotionUpdatesProvider.java From PrivacyStreams with Apache License 2.0 | 5 votes |
@Override protected void provide() { Thread thread = Thread.currentThread(); Thread.UncaughtExceptionHandler wrapped = thread.getUncaughtExceptionHandler(); if (!(wrapped instanceof GoogleApiFixUncaughtExceptionHandler)) { GoogleApiFixUncaughtExceptionHandler handler = new GoogleApiFixUncaughtExceptionHandler(wrapped); thread.setUncaughtExceptionHandler(handler); } // Thread thread = Thread.currentThread(); // thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { // @Override // public void uncaughtException(Thread thread, Throwable throwable) { // System.out.println(thread.getName() + " throws exception: " + throwable); // } // }); client = new GoogleApiClient.Builder(getContext()) //Establish Connection .addApi(Awareness.API) .build(); client.connect(); walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING); //Create Fence onFootFence = DetectedActivityFence.during(DetectedActivityFence.ON_FOOT); runningFence = DetectedActivityFence.during(DetectedActivityFence.RUNNING); intent = new Intent(FENCE_RECEIVER_ACTION); //Set up the intent and intent filter myFillter = new IntentFilter(FENCE_RECEIVER_ACTION); myPendingIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0); //Set up the pendingIntent myFenceReceiver = new FenceReceiver(); //Set up the receiver getContext().registerReceiver(myFenceReceiver, myFillter); registerFence(WALKINGFENCE, walkingFence); //register the fences registerFence(TILTINGFENCE, tiltingFence); registerFence(ONFOOTFENCE, onFootFence); registerFence(RUNNINGFENCE, runningFence); }
Example #26
Source File: SnapshotApiActivity.java From android-samples with Apache License 2.0 | 4 votes |
/** * Get current activity of the user. This is under snapshot api category. * Current activity and confidence level will be displayed on the screen. */ private void getCurrentActivity() { Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient) .setResultCallback(new ResultCallback<DetectedActivityResult>() { @Override public void onResult(@NonNull DetectedActivityResult detectedActivityResult) { if (!detectedActivityResult.getStatus().isSuccess()) { Toast.makeText(SnapshotApiActivity.this, "Could not get the current activity.", Toast.LENGTH_LONG).show(); return; } ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult(); DetectedActivity probableActivity = ar.getMostProbableActivity(); //set the activity name TextView activityName = (TextView) findViewById(R.id.probable_activity_name); switch (probableActivity.getType()) { case DetectedActivity.IN_VEHICLE: activityName.setText("In vehicle"); break; case DetectedActivity.ON_BICYCLE: activityName.setText("On bicycle"); break; case DetectedActivity.ON_FOOT: activityName.setText("On foot"); break; case DetectedActivity.RUNNING: activityName.setText("Running"); break; case DetectedActivity.STILL: activityName.setText("Still"); break; case DetectedActivity.TILTING: activityName.setText("Tilting"); break; case DetectedActivity.UNKNOWN: activityName.setText("Unknown"); break; case DetectedActivity.WALKING: activityName.setText("Walking"); break; } //set the confidante level ProgressBar confidenceLevel = (ProgressBar) findViewById(R.id.probable_activity_confidence); confidenceLevel.setProgress(probableActivity.getConfidence()); //display the time TextView timeTv = (TextView) findViewById(R.id.probable_activity_time); SimpleDateFormat sdf = new SimpleDateFormat("h:mm a dd-MM-yyyy", Locale.getDefault()); timeTv.setText("as on: " + sdf.format(new Date(ar.getTime()))); } }); }
Example #27
Source File: GapiFenceManager.java From JCVD with MIT License | 4 votes |
@VisibleForTesting protected FenceClient createFenceClient() { return Awareness.getFenceClient(mContext); }
Example #28
Source File: MainActivity.java From android-play-awareness with Apache License 2.0 | 4 votes |
/** * 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 #29
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 4 votes |
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() ); }
Example #30
Source File: MainActivity.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 4 votes |
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); } } }); }