Friday, August 12, 2016

Google Play Services: Awareness AP_part 1

Making an application context-aware is one of the best ways to offer useful services to your users. While there are still multiple ways to do this—including geofences, activity recognition, and other location services—Google has recently released the Awareness API, which allows developers to create apps that intelligently react to the user's real world situation. The Awareness API combines the Places API, Locations API, Activity Recognition, and Nearby API, as well as adding support for headphone state and weather detection.

In this tutorial you will learn about the Awareness API and how to access snapshots of data, as well as how to create listeners (known as fences, taking their name from geofences) for combinations of user conditions that match the goals of your applications. This can be useful for a wide variety of apps, such as location-based games, offering coupons to users in stores, and starting a music app when you detect a user exercising. All code for this sample application can be found on GitHub.

1. Setting Up the Developer Console

Before diving into your Android application, you will need to set up Google Play Services through the Google API Console. If you already have a project created, you can skip the first step of this section. If not, you can click the above link and follow along to create a new project for your application.

Step 1: Creating a Project
To create a new project, click on the blue Create Project button in the top center of the screen.


This presents you with a dialog that asks for a project name. For this tutorial, I have created a project called TutsPlusAwareness. There are some restrictions on what you can name your project as only letters, numbers, quotes, hyphens, spaces, and exclamation points are allowed characters.


Once you hit Create, a dialog appears in the lower right corner of the page indicating that the project is being created. Once it has disappeared, your project will be available for setting up. You should see a screen similar to the following. If not, click on the Google APIs logo in the top left corner to be taken to the API manager screen.


Step 2: Enabling the Necessary API
From the Google APIs Overview screen, select the search box and search for the Awareness API.


Once you have selected Awareness API from the returned results, click on the blue Enable button to allow your app to use the Awareness API. If this is the first API you have enabled, you will be prompted to create a set of credentials. Continue to the Credentials page for step 3 of this tutorial.


In addition to the Awareness API, there are additional APIs that you may need to enable. If your app uses the Places functionality of the Awareness API, you will need to enable Google Places API for Android.

If your app uses beacons, you will also need to enable the Nearby Messages API.

Step 3: Creating An Android API Key
In order to use the enabled APIs, you will need to generate an API key for your Android app. On the credentials page for your Google project, select Awareness API from the top dropdown menu and Android from the second.

Next you will be taken to a screen where you can enter a package name for your app and the SHA1 certificate for the app's signing key. In order to get the signing key for your debug key on Linux or OS X, enter the following command in a terminal window.
  1. keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
On Windows, you can run the same command with the path set to the location of your debug.keystore file.

Once you click the Create API key button, you will be given the API key that you will need to use in your Android application.


2. Setting Up the Android Project

Once you have an API key created and the proper APIs enabled, it's time to start setting up your Android project. For this tutorial, we'll create a test application in order to learn the API.

In order to demonstrate all of the features of the Awareness API, this tutorial will focus on using a simple list representing each feature used. Although the details of creating this list will not be discussed, you can find a complete implementation in the GitHub source for this tutorial.

Step 1: Set Up Play Services
First you will need to include the Play Services library in your build.gradle file. While you can include all of Google Play Services, it's best to include only the packages you need for your app.

In this case, the Awareness API is available in the ContextManager package, and it can be included in your project by adding the following line within your dependencies node. You will also want to make sure the AppCompat library is included, as this will be used for checking permissions on Marshmallow and above devices.
  1. compile 'com.google.android.gms:play-services-contextmanager:9.2.0'
  2. compile 'com.android.support:appcompat-v7:23.4.0'
Once you have added the above line, sync your project and open the strings.xml file for your project. You will want to place your API key from the Google API Console into a string value.
  1. <string name="google_play_services_key">YOUR API KEY HERE</string>
After you have added your API key, you will need to open your project's AndroidManifest.xml file. Depending on what features of the Awareness API you use, you will need to include permissions for your app. If your app uses the beacon, location, places or weather functionality of the Awareness API, then you will need to include the ACCESS_FINE_LOCATION permission. If you need to use the activity recognition functionality, then you will require the ACTIVITY_RECOGNITION permission.
  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  2. <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
Next you will need to declare meta-data within the application node that ties your app to the Google API services. Depending on what your app uses, you will need to also include the com.google.android.geo and com.google.android.nearby metadata for using location, beacons and places features.
  1. <meta-data
  2.     android:name="com.google.android.awareness.API_KEY"
  3.     android:value="@string/google_play_services_key" />
  4.  
  5. <!-- places/location declaration -->
  6. <meta-data
  7.     android:name="com.google.android.geo.API_KEY"
  8.     android:value="@string/google_play_services_key" />
  9.  
  10. <!-- Beacon snapshots/fences declaration -->
  11. <meta-data
  12.     android:name="com.google.android.nearby.messages.API_KEY"
  13.     android:value="@string/google_play_services_key" />
Next you will need to open your MainActivity.java file. Add the GoogleApiClient.OnConnectionFailedListener interface to your class and connect to Google Play Services and the Awareness API in your onCreate(Bundle) method.
  1. public class MainActivity extends AppCompatActivity implements
  2.         GoogleApiClient.OnConnectionFailedListener {
  3.              
  4.     @Override
  5.     protected void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.activity_main);
  8.  
  9.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  10.                 .addApi(Awareness.API)
  11.                 .enableAutoManage(this, this)
  12.                 .build();
  13.         mGoogleApiClient.connect();
  14.     }
  15.      
  16.     @Override
  17.     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}
  18. }
Step 2: Permissions
Now that Play Services are configured within your Android app, you will need to ensure that your users on Android Marshmallow or higher have granted permission for your application to use their location. You can check for this permission in onCreate(Bundle) and before you access any features that require the location permission in order to avoid crashes within your app.
  1. private boolean checkLocationPermission() {
  2.     if( !hasLocationPermission() ) {
  3.         Log.e("Tuts+", "Does not have location permission granted");
  4.         requestLocationPermission();
  5.         return false;
  6.     }
  7.  
  8.     return true;
  9. }
  10.  
  11. private boolean hasLocationPermission() {
  12.     return ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION )
  13.             == PackageManager.PERMISSION_GRANTED;
  14. }
If the location permission has not already been granted, you can then request that the user grant it.
  1. private final static int REQUEST_PERMISSION_RESULT_CODE = 42;
  2.  
  3. private void requestLocationPermission() {
  4.     ActivityCompat.requestPermissions(
  5.             MainActivity.this,
  6.             new String[]{ Manifest.permission.ACCESS_FINE_LOCATION },
  7.             REQUEST_PERMISSION_RESULT_CODE );
  8. }
This will cause a system dialog to appear asking the user if they would like to grant permission to your app to know their location.

When the user has responded, the onRequestPermissionsResult() callback will receive the results, and your app can respond accordingly.
  1. @Override
  2. public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
  3.                                        @NonNull int[] grantResults) {
  4.     switch (requestCode) {
  5.         case REQUEST_PERMISSION_RESULT_CODE: {
  6.             // If request is cancelled, the result arrays are empty.
  7.             if (grantResults.length > 0
  8.                     && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  9.                 //granted
  10.             } else {
  11.                 Log.e("Tuts+", "Location permission denied.");
  12.             }
  13.         }
  14.     }
  15. }
At this point you should be finished setting up your application for use of the Awareness API.
Written  by Paul Trebilcox-Ruiz

If you found this post interesting, follow and support us.
Suggest for you:

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps

Python For Android Hacking Crash Course: Trojan Perspective

No comments:

Post a Comment