Android location services permission

Exploring Android Q: Location Permissions

Last week we saw the announcement of the Android Q beta release

With this version of Android comes a collection of exciting changes which we need to get our apps ready for. In this set of articles I’m going to be diving into each one of these so that we are fully prepared for getting our apps ready!

Note: You can find the code for this article here.

As outlined in the beta release notes for Android Q, one of the changes we are seeing introduced is the way in which we work with user locations inside of our applications — these changes affect the access of the location in both the foreground and background. This gives our users more control of when they wish apps to be able to access their location — allowing them to restricting it to only when the app is currently in use. In this post I want to take a quick dive into how these changes will effect apps, along with what we need to do to adapt to these changes.

Foreground Location Permission

There may be cases where an application requires access to the users location whilst there is a continuation of user-initiated actions. For example, maybe your app delivers navigation to the user — once the user navigates to their home screen from your app, you’ll want to continue having access to their location in-order to continue serving navigation to them. If you’re utilising a foreground service to handle this functionality then we’ll only need foreground access to the users location, as there’s no reason for us to access the users location from the background (we’ll cover the case where we may not be using a foreground service in the next section.). When your application requires access to this location data, it’s important to let your user know why when accessing it.

To begin with, any service of this kind that makes use of the users location needs to be declared as a location foreground service. This can be done by making use of the foregroundServiceType when declaring your service within your manifest file.

Before we try to kick off our foreground service we need to ensure that we have the required permission from the user to do so. We can do this by checking for the ACCESS_COARSE_LOCATION permission. Now, this isn’t a new permission — in fact, it’s been around since API level 1. However, we only previously needed to define within our application manifest file — now we must request this permission at runtime. You can see how this now gives our user much more control over how this permission is used.

In this code above you can see that we begin by checking whether we have the location permission. If so, we can continue to handle the location flow or otherwise, we must request the permission from the user. If this is the case, then we will receive the permission state within the onRequestPermissionsResult() callback within our calling class.

When we request this permission, our user will be displayed the following dialog:

As you can see, the intent of the permission has been made quite clear — our app will only have access to their location whilst in the foreground (as in, the app is being used). If the user has denied this permission at any point and we request it again, then they will be shown a slight variation of the dialog:

Читайте также:  Звук сам выключается андроид

Similar to how the runtime permissions in android usually work, we know are shown an option where the user can request not to be asked again. Because of this functionality, it’s important that you only ask for this foreground location access at the point it is required. This guides your user as to why the permission is required in the current context, rather than give the feeling that it is being asked for no reason.

Background location permission

When it comes to accessing the user location when our app is backgrounded, things work a little bit differently. We first need to add a new permission to our manifest file, this is the ACCESS_BACKGROUND_LOCATION permission. Although this is declared in the manifest, it can still be revoked at any time by the user.

Note that here we aren’t required to add the foregroundServiceType service type to our service declaration, this is because we don’t need momentary permission to run outside of our app — this background permission already gives our application the ability to do this.

As well as the above, the permission needs to be granted by the user at runtime. So before we try and access the users location from the background, we need to ensure that we have the required permission from the user to do so. We can do this by checking for the ACCESS_BACKGROUND_LOCATION permission. You can see again how this now gives our user much more control over how this permission is used and avoids background location access being abused.

Our code for checking the permission may look something like this:

You’ll notice that this code is pretty similar to the checks that we defined for the foreground location permission. Here we check for both permissions, giving us a fallback in location retrieval should the user deny us background access for some reason.

When we request this permission, our user will be displayed the following dialog:

The intent of the permission has been made quite clear — our app will be able to access their location whilst in the background. If the user has denied this permission at any point and we request it again, then they will be shown a slight variation of the dialog:

Similar to how the runtime permissions in android usually work, we know are shown an option where the user can request not to be asked again. Because of this functionality, it’s important that you only ask for this background location access at the point it is required. This guides your user as to why the permission is required in the current context, rather than give the feeling that it is being asked for no reason.

We can see from this article that Android Q changes the way in which our applications works with location permissions. Our apps will no longer be able to freely access the user locations from services, whether in the foreground or background. To support backward compatibility, if your application doesn’t target Q then the ACCESS_BACKGROUND_LOCATION permission will be added if the COARSE or FINE permissions are declared. Similarly, requesting either of the two at runtime will also grant the permission.

These changes give our users more control over how applications access their location, allowing us to create apps with the users privacy and safety in mind. Any questions about these location changes? Feel free to reach out in the comments!

Источник

Исследование Android Q: Location Permissions

Перевод статьи о нововведениях версии мобильной операционной системы Android Q. В этой статье речь пойдет о Location Permissions — разрешениях доступа к местоположению их типах и способах предоставления.

Читайте также:  Как сохранить все контакты андроид

Недавно мы увидели анонс бета-версии Android Q. В этой версии Android появилась коллекция интересных изменений, к которым нам нужно подготовить наши приложения. В этом наборе статей я собираюсь углубиться в каждую из них, чтобы мы были полностью готовы к тому, чтобы подготовить наши приложения!

Примечание. Код этой статьи можно найти здесь.

Как указано в примечаниях к бета-версии для Android Q, одним из изменений, которые мы видим, является то, как мы работаем с пользовательскими местоположениями внутри наших приложений — эти изменения влияют на доступ к местоположению как на переднем, так и на заднем плане. Это дает нашим пользователям больший контроль над тем, когда они хотят, чтобы приложения могли иметь доступ к их местоположению, что позволяет им ограничивать его только в том случае, если приложение используется в данный момент. В этой статье я хочу кратко остановиться на том, как эти изменения повлияют на приложения, а также на то, что нам нужно сделать, чтобы адаптироваться к этим изменениям.

Foreground Location Permission

Могут быть случаи, когда вашему приложению требуется доступ к местоположению пользователя во время работы на переднем плане. Например, может быть, ваше приложение обеспечивает навигацию для пользователя — как только пользователь перейдет на свой домашний экран из вашего приложения, приложение продолжит получение доступа к местоположению, чтобы продолжить обслуживание навигации. Если вашему приложению требуется доступ к этим данным о местоположении, важно сообщить пользователю, о доступе приложения к его местоположению.

Для начала, любой сервис такого рода, который использует местоположение пользователей, должен быть объявлен как сервис переднего плана местоположения. Это можно сделать, используя foregroundServiceType при объявлении службы в файле манифеста.

Источник

Understanding and Implementing Location Permission in Android Q

With Android Q releasing in Beta, there are a lot of new things coming to the Android Eco-System with it.

Privacy was the main focus with the Andorid Q release and with better handling of permissions, Background use, UI etc. A new permission was also introduced Activity Recognition Permission.But, In this blog we will be specifically talking about Location Permission in Android Q.

History about Location Services :

Location Services has evolved and has matured since the early days.At first we could use background services and take location updates «n» times a day but in coming years keeping privacy in focus developer can only take updates a few time only.

Since Android Oreo, it was recommended to take location updates using Foreground Services as it had no limit like background services and user can also see the updates coming from the notification tray.

This can be done using adding foregroundServiceType in the manifest file,

But, to make sure location works, we need to add ACCESS_COARSE_LOCATION in the project.

But in Android Q,

The whole world changed for Location Services in Q. Now, user had a lot of control on what to give as permission and what not too. Also user can permit appto get location updates in background as well. Let’s discuss the it in step by step,

Step 01 :

Here, in the Manifest we don’t need to specifically add the foregroundServiceType in manifest file.

Using Background Location with Access Coarse Location we can get 3 options for users to select from,

Step 02 :

in your build.gradle of your app,

In the above code, you can see targetSdkVersion has been set to Q

Step 03 :

Let’s ask the permission in Our Activity file,

Here , in the above code we can only permit the background location if and only the foreground location is pemitted.

Now, lets run the app and we will see the following pop-up with a new re-design of material component

and if we click Deny here,

Читайте также:  Вконтакте версия айфона для андроид

To read more about the Permissions in Andorid Q, Click here.

Источник

Google Play Services and Runtime Permissions

Since Android 6.0 Marshmallow, Android uses a permissions model that streamlines the app install and auto-update process. Permissions are requested at runtime instead of before app installation. Additionally, users can choose to deny specific permissions. To give users this flexibility, you need to make sure that your app behaves as expected when a user enables or disables a specific permission.

Google Play services itself has runtime permissions that users can choose to deny separately from those permissions specifically requested by your application. Google Play services automatically obtains all permissions it needs to support its APIs. However, your app should still check and request runtime permissions as necessary and appropriately handle errors in cases where a user has denied Google Play services a permission required for an API your app uses.

It’s good practice to manage the user’s expectations in setting permissions that the runtime may require. The following best practices will help you avoid potential issues.

Prerequisites

You’ll need to declare permissions in your AndroidManifest.xml file. For example:

Guidelines

Verify permissions before calling APIs

Once you’ve declared the APIs that you want to use in your AndroidManifest.xml file, ensure that you have the required permission before calling an API. This can be done using the checkSelfPermission method of ActivityCompat or ContextCompat .

If the call returns false this means the permissions aren’t granted and you should use requestPermissions to request them. The response to this is returned in a callback which you will see in the next step.

Implement the request permission callback

If the permission your app needs hasn’t been granted by the user, the requestPermissions method should be called to ask the user to grant them. The response from the user is captured in the onRequestPermissionsResult callback. Your app should implement this and always check the return values because the request could be denied or canceled. You can also request and check for multiple permissions at once—the following sample only checks for a single permission.

Show the permission rationale

If the permissions your app requests are necessary for the core features of the app and the user has previously denied the permission request, your app should display an additional explanation before requesting the permission again. Users are more likely to grant permissions when they understand the why the permission is needed and the immediate benefit for them.

In this case, before the calling requestPermissions , you should call shouldShowRequestPermissionRationale . If it returns true, you should create some UI to display additional context for the permission.

For example, your code might look like this:

Handle connection failures

If your app uses the deprecated GoogleApiClient , when you call connect() , Google Play services validates that it has all the necessary permissions needed. connect() fails when any permission groups needed by Google Play services itself are missing.

If the call to connect() fails, ensure your app handles the connection failure correctly. If Google Play services itself is missing permissions, you can invoke startResolutionForResult() to initiate the user flow to fix them.

Newer GoogleApi -based API calls will automatically display either a dialog (if the client is instantiated with an Activity ) or system tray notification (if the client is instantiated with a Context ) that the user can tap to start the permissions resolution intent. Calls will be enqueued and retried once the permission is granted.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Оцените статью