Tag Archives: permissions

Google Play services 8.1: Get ready for Marshmallow!

Posted by, Magnus Hyytsten, Developer Advocate

With the rollout of Google Play services 8.1 finally finished, there’s a lot of new information to share with developers about the release!

Marshmallow Permissions

Android 6.0 (Marshmallow) has introduced a new permissions model allowing users to control app permissions at runtime. As an app developer, it’s important for you to adopt this and give your users good control over the permissions your app needs. You can find more details here.

If your app is using Google Play services SDK versions prior to 8.1, you must update to use this new version to ensure your app is fully compatible with Android 6.0. This will enable you to manage the permission flows appropriately for your app and avoid any potential connection issues. For more details, and a step-by-step guide to what your app should do for the best user experience, take a look at this blog post on the Android Developers site.

App Invites

App Invites allows you to grow your apps audience by letting existing Android and iOS users invite their Google contacts via email or SMS to try your app out. Google Play services 8.1 adds the ability for developers to customize the email invitation, including adding a custom image, and specifying a call-to-action button text. These improvements should help developers increase user engagement and conversions with app invites.

Ambient Mode Maps

Android Wear provides a feature called ambient mode, enabling apps to stay visible, even when they aren’t actively being used. Now, with Google Play services 8.1, the Google Maps Android API supports ambient mode. In this mode, a simplified low-color rendering of the map will be seen. This reduces power consumption by lighting fewer pixels, but the camera and zoom level are retained, so user context will be kept. To learn more about ambient mode, check out this blog post.

Nearby Status Listener

Google Nearby allows you to build simple interactions between nearby devices. A new addition in Google Play services allows your app to receive callbacks when an active Nearby publish or subscribe expires. This frees you from tracking the TTL and allows your app's UI to accurately reflect whether Nearby is active or not.

Play Games Player Stats API

The new Play Games Player Stats API allows you to build better, smarter, games. It will let you tailor user experiences to specific segments of players and different stages of the player lifecycle. For example, you can give your most valuable players that are returning from a break in play a special welcome back message and reward.

Breaking Changes

In this release, there are some changes to GoogleApiClient and PendingResult, making them abstract classes, which may lead to breaking changes in your code. Learn more about these changes and how to handle them in the release notes.



SDK Now available!

You can get started developing today by downloading the Google Play services SDK from the Android SDK Manager. To learn more about Google Play services and the APIs available to you through it, visit our documentation on Google Developers.

Google Play services 8.1 and Android 6.0 Permissions

Posted by, Laurence Moroney, Developer Advocate

Along with new platform features, Android 6.0 Marshmallow has a new permissions model that streamlines the app install and auto-update process. Google Play services 8.1 is the first release to support runtime permissions on devices running Android 6.0. and will obtain all the permissions it needs to support its APIs. As a result, your apps won’t normally need to request permissions to use them. However, if you update your apps to target API level 23, they will still need to check and request runtime permissions, as necessary.

To update your Google Play services apps to handle the latest permissions model, it’s good practice to manage the user’s expectations in setting permissions that the runtime may require. Below are some best practices to help you get started.

Before you begin...

For the purposes of this post, ensure that your API level and Target SDK are set to at least 23. Additionally, ensure that, for backwards compatibility, you are using the V4 support library to verify and request permissions. If you don’t have it already, add it to your gradle file:

 
com.android.support:support-v4:23.0.1

You’ll also need to declare Permissions in your AndroidManifest.xml file. There’s no change here. Whatever permissions your app has always needed should be declared in your AndroidManifest.xml file with the uses-permission tag. Here’s an example:

 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Documentation on maps and location, including a walkthrough on connecting may be found here.

Step 1. Manage Connections to the GoogleApiClient

Make sure that you are handling connection failures on GoogleApiClient correctly, and that you are using the proper resolution process as outlined here. Note that if Google Play services itself is missing permissions, the user flow to fix them will be handled for you automatically if you follow this methodology.

Here’s an example:

 
@Override
public void onConnectionFailed(ConnectionResult result) {
      if (mResolvingError) {
             // Already attempting to resolve an error.
             return;
      } else if (result.hasResolution()) {
             try {
                   mResolvingError = true;
                   result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
             } catch (SendIntentException e) {
                   // There was an error with the resolution intent. Try again.
                   mGoogleApiClient.connect();
             }
      } else {
             // Show dialog using GooglePlayServicesUtil.getErrorDialog()
             showErrorDialog(result.getErrorCode());
             mResolvingError = true;
      }
}

Step 2. Verify Permissions before calling APIs

It’s easy to assume that once you can connect, and you’ve declared the required permissions for APIs that you want to use in your AndroidManifest.xml file, that future calls will be fine. However, it is vital to ensure that you have the required permission before calling an API or connecting to the GoogleApiClient. This can be done using the checkSelfPermission method of ActivityCompat, Fragment or ContextCompat.

If the call returns false, i.e. the permissions aren’t granted, you’ll use requestPermissions to request them. The response to this will be returned in a callback which you will see in the next step.

Here’s an example:

 
private static final int REQUEST_CODE_LOCATION = 2;

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
 // Request missing location permission.
 ActivityCompat.requestPermissions(this, 
    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
    REQUEST_CODE_LOCATION);
} else {
 // Location permission has been granted, continue as usual.
 Location myLocation = 
             LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

Step 3. Implement the request permission callback.

In step 2, if the permission wasn’t granted by the user, the requestPermissions method was called to ask the user to grant them. The response from the user is captured in the onRequestPermissionsResult callback. You need to implement this, and always check the return values because the request could be denied or cancelled. Note that you might need to request multiple permissions here -- this sample just checks for a single permission -- you may need to check for more.

 
public void onRequestPermissionsResult(int requestCode, 
                                      String[] permissions,
                                      int[] grantResults) {
     if (requestCode == REQUEST_CODE_LOCATION) {
          if(grantResults.length == 1 
       && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          // success!
          Location myLocation =
               LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
     } else {
     // Permission was denied or request was cancelled
     }
}

Step 4. Show permission rationale

If the user has previously denied the permission request, your app should display an additional explanation before requesting the permission again. Indeed, if the permissions are non trivial for the core features of the app, and the user is confused as to why they are needed, it would be recommended to guide them.

In this case, before the call to requestPermissions (step 2, above), you should call shouldShowRequestPermissionRationale, and if it returns true, you should create some UI to display additional context for the permission.

As such your code from Step 2 might look like this:

private static final int REQUEST_CODE_LOCATION = 2;

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
 // Check Permissions Now

  if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
        // Display UI and wait for user interaction
  } else {
 ActivityCompat.requestPermissions(
             this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
                                     REQUEST_CODE_LOCATION);
  }
} else {
     // permission has been granted, continue as usual
     Location myLocation = 
        LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

Note that in this case your user may still deny the permissions, in which case you will need to craft your app so as not to be in a situation where a denied permission affects parts of the app where it shouldn’t. Refer to the best practices section on the Android developer’s site for more details and guidance.

If you’ve built any applications that use Google Play services, I’d recommend that you download the Google Play services 8.1 SDK, and rebuild your applications using it, testing against the most recent versions of Android 6.0, which you can download from the Android Developers site.

Useful resources:

Get started with building for Android 6.0

Android Permissions design guidelines

Google IO 2015 Session on Android M Permissions

Samples for Google Play services 8.1 with coding best practices

New permissions requirements for Android TV

Posted by Anirudh Dewani, Developer Advocate

Android 6.0 introduces a new runtime permission model that gives users more granular control over granting permissions requested from their apps and leads to faster app installs. Users can also revoke these permissions from Settings at any point of time. If an app running on the M Preview supports the new permissions model, the user does not have to grant any permissions when they install or upgrade the app. Developers should check for permissions that require runtime grant from users, and request them if the app doesn’t already have them.

To list all permissions that require runtime grant from users on Android 6.0 -

adb shell pm list permissions -g -d 

RECORD_AUDIO

Apps should generally request as few permissions as possible. Voice search is an integral part of Android TV content discovery experience. When using the internal SpeechRecognizer to enable Voice Search, apps must declare RECORD_AUDIO permission in the manifest. RECORD_AUDIO requires explicit user grant during runtime in Android 6.0. When using the Android TV Leanback support library, apps can eliminate the need for requesting RECORD_AUDIO during runtime by using SpeechRecognitionCallback instead of SpeechRecognizer.

SearchActivity.java

Commit from Android TV Leanback Sample repository.


mFragment = (SearchFragment) getFragmentManager()
                .findFragmentById(R.id.search_fragment);

if (!USE_INTERNAL_SPEECH_RECOGNIZER) {
   
    mSpeechRecognitionCallback = new SpeechRecognitionCallback() {
        
        @Override
        public void recognizeSpeech() {
            if (DEBUG) Log.v(TAG, "recognizeSpeech");
        
            // ACTION_RECOGNIZE_SPEECH
            startActivityForResult(mFragment.getRecognizerIntent(), REQUEST_SPEECH);
        }
    };
    mFragment.setSpeechRecognitionCallback(mSpeechRecognitionCallback);
}


When SpeechRecognitionCallback is set, Android Leanback support library will let the your activity process the voice search action instead of using the internal SpeechRecognizer. The app can then use RecognizerIntent to support speech recognition.

If you have an Android TV app targeting API Level 23, please update the app to use SpeechRecognitionCallback and remove RECORD_AUDIO permission from your manifest.

Building better apps with Runtime Permissions

Posted by Ian Lake, Developer Advocate

Android devices do a lot, whether it is taking pictures, getting directions or making phone calls. With all of this functionality comes a large amount of very sensitive user data including contacts, calendar appointments, current location, and more. This sensitive information is protected by permissions, which each app must have before being able to access the data. Android 6.0 Marshmallow introduces one of the largest changes to the permissions model with the addition of runtime permissions, a new permission model that replaces the existing install time permissions model when you target API 23 and the app is running on an Android 6.0+ device.

Runtime permissions give your app the ability to control when and with what context you’ll ask for permissions. This means that users installing your app from Google Play will not be required to accept a list of permissions before installing your app, making it easy for users to get directly into your app. It also means that if your app adds new permissions, app updates will not be blocked until the user accepts the new permissions. Instead, your app can ask for the newly added runtime permissions as needed.

Finding the right time to ask for runtime permissions has an important impact on your app’s user experience. We’ve gathered a number of design patterns in our new Permission design guidelines including best practices around when to request permissions, how to explain why permissions are needed, and how to handle permissions being denied.

Ask up front for permissions that are obvious

In many cases, you can avoid permissions altogether by using the existing intents system to utilize other existing specialized apps rather than building a full experience within your app. An example of this is using ACTION_IMAGE_CAPTURE to start an existing camera app the user is familiar with rather than building your own camera experience. Learn more about permissions versus intents.

However, if you do need a runtime permission, there’s a number of tools to help you. Checking for whether your app has a permission is possible with ContextCompat.checkSelfPermission() (available as part of revision 23 of the support-v4 library for backward compatibility) and requesting permissions can be done with requestPermissions(), bringing up the system controlled permissions dialog to allow the user to grant you the requested permission(s) if you don’t already have them. Keep in mind that users can revoke permissions at any time through the system settings so you should always check permissions every time.

A special note should be made around shouldShowRequestPermissionRationale(). This method returns true if the user has denied your permission request at least once yet have not selected the ‘Don’t ask again’ option (which appears the second or later time the permission dialog appears). This gives you an opportunity to provide additional education around the feature and why you need the given permission. Learn more about explaining why the app needs permissions.

Read through the design guidelines and our developer guide for all of the details in getting your app ready for Android 6.0 and runtime permissions. Making it easy to install your app and providing context around accessing user’s sensitive data are key changes you can make to build better apps.

Android M Developer Preview & Tools

By Jamal Eason, Product Manager, Android

Today at Google I/O, we announced a developer preview of the next version of Android, the M release. Last year’s developer preview was a first for Android and we received great feedback. We want to continue to give you developers early access to Android so you have time to get your apps ready for the next version of Android. This time with the M Developer Preview, we will provide a clear timeline for testing and feedback plus more updates to the preview build.

Visit the M Developer Preview for downloads and documentation

The Android M release: improving the fundamentals

For the M release, we focused on improving the core user experience of Android, from fixing thousands of bugs, to making some big changes to the fundamentals of the platform:

  • Permissions - We are giving users control of app permissions in the M release. Apps can trigger requests for permissions at runtime, in the right context, and users can choose whether to grant the permission. Making permission requests right when they’re needed means users can get up and running in your app faster. Also, users have easy access to manage all their app permissions in settings. On M, as a developer, you should design your app to prompt for permissions in context and account for permissions that don’t get granted. As more devices upgrade to M, app permission behavior will be a critical development flow to test.
  • Runtime App Permissions

  • App links - We are making it even easier to link between apps. Android has always allowed apps to register to natively handle URLs. Now you can add an autoVerify attribute to your app manifest so that users can be linked deep into your native app without any disambiguation prompt. App links, along with App Indexing for Google search, make it easier for users to discover and re-engage with your app.
  • Battery - We’re making Android devices smarter about managing power through a new feature called Doze. With M, Android uses significant motion detection to learn if a device has been left unattended for a while. In this state, Android will exponentially back off background activity, trading off a little bit of app freshness for longer battery life. Consider how this may affect your app; for instance, if you’re building a chat app, you may want to make use of high priority messages to wake your app when the device is dozing.

The Android M release: advancing assistance and payments

We are also delighted to announce a couple of big new features:

  • Now on tap - We are making it even easier for Android users to get assistance with Now on tap -- whenever they need it, wherever they are on their device. For example, if your friend texts you about dinner at a new restaurant, without leaving the app, you can ask Google Now for help. Using just that context, Google can find menus, reviews, help you book a table, navigate there, and deep link you into relevant apps. As a developer, you can implement App Indexing for Google search to let users discover and re-engage with your app through Now on tap.
  • Now on tap

  • Android Pay & Fingerprint - We’ve built on our work with Near Field Communications (NFC) in Gingerbread and Host Card Emulation in Kitkat to develop Android Pay. Android Pay will enable Android users to simply and securely use their Android phone to pay in stores or in thousands of Android Pay partner apps. With M, native fingerprint support enhances Android Pay by allowing users to confirm a purchase with their fingerprint. Moreover, fingerprint on M can be used to unlock devices and make purchases on Google Play. With new APIs in M, it’s easy for you to add fingerprint authorization to your app and have it work consistently across a range of devices and sensors.

These are just a few highlights from the M Developer Preview that we announced today. The M preview will be available for download right after the keynote.

Android Developer Tools

In addition to the developer preview, we are launching new tools to help you in the development of your Android App:

  • Android Studio v1.3 Preview - To help take advantage of the M Developer Preview features, we are releasing a new version of Android Studio. Most notable is a much requested feature from our Android NDK & game developers: code editing and debugging for C/C++ code. Based on JetBrains Clion platform, the Android Studio NDK plugin provides features such as refactoring and code completion for C/C++ code alongside your Java code. Java and C/C++ code support is integrated into one development experience free of charge for Android app developers. Update to Android Studio v1.3 via the Canary channel and let us know what you think.
  • Android Studio 1.3 with Android NDK Support

  • Android Design Support Library - Making Material design apps gets even easier with the new Android Design support library. We have packaged a set a key design components (e.g floating action button, snackbar, navigation view, motion enabled Toolbars) that are backward compatible to API 7 and can be added to your app to create a modern, great looking Android app without building everything from scratch.
  • Google Play Services - Today we also are releasing v7.5 of Google Play services which includes new features ranging from Smart Lock for Passwords, new APIs for Google Cloud Messaging and Google Cast, to Google Maps API on Android Wear devices.

Get Started

The M Developer Preview includes an updated SDK with tools, system images for testing on the official Android emulator, and system images for testing on Nexus 5, Nexus 6, Nexus 9, and Nexus Player devices. We are excited to expand the program and give you more time to ensure your apps support M when it launches this fall. Based on your feedback, we plan to update the M Developer preview system images often during the developer preview program. The sooner we hear from you, the more feedback we can integrate, so let us know!

To get started with the M Developer Preview and prepare your apps for the full release, just follow these steps:

  1. Update to Android Studio v1.3+ Preview
  2. Visit the M Developer Preview site for downloads and documentation.
  3. Explore the new APIs & App Permissions changes
  4. Explore the Android Design Support Library & Google Play Services APIs
  5. Get the emulator system images through the SDK Manager or download the Nexus device system images.
  6. Test your app with your supported Nexus device or emulator
  7. Give us feedback