- Исследование Android Q: Location Permissions
- Foreground Location Permission
- Best way to get user GPS location in background in Android [duplicate]
- 13 Answers 13
- Getting User’s Location Without Permission
- 1 Answer 1
- Exploring Android Q: Location Permissions
- Foreground Location Permission
- Background location permission
- How to get user location in Android
- Approach
Исследование Android Q: Location Permissions
Перевод статьи о нововведениях версии мобильной операционной системы Android Q. В этой статье речь пойдет о Location Permissions — разрешениях доступа к местоположению их типах и способах предоставления.
Недавно мы увидели анонс бета-версии Android Q. В этой версии Android появилась коллекция интересных изменений, к которым нам нужно подготовить наши приложения. В этом наборе статей я собираюсь углубиться в каждую из них, чтобы мы были полностью готовы к тому, чтобы подготовить наши приложения!
Примечание. Код этой статьи можно найти здесь.
Как указано в примечаниях к бета-версии для Android Q, одним из изменений, которые мы видим, является то, как мы работаем с пользовательскими местоположениями внутри наших приложений — эти изменения влияют на доступ к местоположению как на переднем, так и на заднем плане. Это дает нашим пользователям больший контроль над тем, когда они хотят, чтобы приложения могли иметь доступ к их местоположению, что позволяет им ограничивать его только в том случае, если приложение используется в данный момент. В этой статье я хочу кратко остановиться на том, как эти изменения повлияют на приложения, а также на то, что нам нужно сделать, чтобы адаптироваться к этим изменениям.
Foreground Location Permission
Могут быть случаи, когда вашему приложению требуется доступ к местоположению пользователя во время работы на переднем плане. Например, может быть, ваше приложение обеспечивает навигацию для пользователя — как только пользователь перейдет на свой домашний экран из вашего приложения, приложение продолжит получение доступа к местоположению, чтобы продолжить обслуживание навигации. Если вашему приложению требуется доступ к этим данным о местоположении, важно сообщить пользователю, о доступе приложения к его местоположению.
Для начала, любой сервис такого рода, который использует местоположение пользователей, должен быть объявлен как сервис переднего плана местоположения. Это можно сделать, используя foregroundServiceType при объявлении службы в файле манифеста.
Источник
Best way to get user GPS location in background in Android [duplicate]
In my android app i want to get user current location every few minute interval and update in to my center server using web service. Currently i am using Fused Location Provide for get user current location, See link
now i want to know what is the best way to get user location frequently and call web service.
below is my code which gives me user current location: —
now from where i have to call this code. Can i use this in a background service or some where else.
Please provide your idea.
13 Answers 13
None of the rest of the answers use:
Which is the Fused Location Provider and the main entry point for interacting with the fused location provider by Google, and it is very hard to find a good example. This was released mid 2017 by Google.
Google Play services location APIs are preferred over the Android framework location APIs (android.location)
If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.
For you to use the Google Location API, first add this to your build.gradle
Then you can use this class Wherebouts.java :
From your Activity, you can use it like this, by passing a Workable object. A Workable object is nothing more than a custom Callback alike object.
By using a callback like Workable, you will write UI related code in your Activity and leave the hustle of working with GPS to a helper class, like Wherebouts.
Of course you would need to ask for the corresponding permissions to the Android OS for your App to use. You can read the following documentation for more info about that or do some research.
Источник
Getting User’s Location Without Permission
This website finds my location with a reasonable presicion. If i use mobilephone the website finds my exact location. If it is possible without asking permission why most of them asks me before getting my location? Isn’t it makes personal security vulnerabilities?
1 Answer 1
From the same page you gave us:
Webkay uses the Google Geolocation API to locate you. This is an educated guess and never as accurate as a GPS Location. The accuracy depends on your location and also on your connection type. If you are on a mobile network expect an error of up to 50km. This example just tries to demonstrate how accurate a website can guess your location without asking you for permission to access your GPS.
A site only needs permission, if it wants to enable your device’s GPS. Also, without the permission, the guessed location is heavily dependent on your mobile carrier signal and IP address. If you are in a location with a lot of mobile towers, the location (obviously) will get more precise.
A site can use the information from all near mobile towers around you to triangulate the position and guess where you are. Think of it like a mesh.
For example: I am using a computer to write this now and the location is easy
100km off, because it has only my IP adress to estimate the location.
Источник
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!
Источник
How to get user location in Android
Many apps in Android uses user’s locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user’s latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query: https://www.google.com/maps/search/?api=1&query=,
Note: The app will run completely fine on an actual device but might show an error on an emulator. So, please try to run it on an actual device!
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Approach
Step 1. Acquiring Permissions
Since using the user’s permission is a matter concerned with high privacy, first acquire the user’s permission to use their location by requesting them for it. From Android 6.0(Marshmallow), the concept of run-time permissions was rolled in and so the same will be used for getting permission. Any of the following permissions can be used for this:
ACCESS_COARSE_LOCATION: It provides location accuracy within a city block.
ACCESS_FINE_LOCATION: It provides a more accurate location. To do this, it needs to do some heavy lifting so it’s recommended to use this only when we need an accurate location.
In case the app needs to access the user’s location while the app is running in the background, we need to add the following permission along with the above ones:
We need to add all these permissions in the AndroidManifest.xml. To access this file, select your project view as Android and click on:
app->manifests->AndroidManifest.xml.
After adding all the permissions, this is how the AndroidManifest.xml file looks like:
Also, as Google’s PlayServices will be used to access the device’s location, add it in dependencies, in the Build.Gradle (app) file:
Step 2. Designing the layout
As the app is fairly simple, it would contain only the MainActivity and hence a single main layout. In the layout, add an ImageView and two TextViews which would be displaying the user’s latitude and longitude. The latitude and longitude which would be displayed will be returned from the logic of our MainActivity which will be discussed next. Here’s how activity_main.xml looks like:
Output:
Step 3. Writing the logic
- To work on the main logic of our app, we will follow the following key points:
- Check if the permissions we request are enabled.
- Else request the permissions.
- If permissions are accepted and the location is enabled, get the last location of the user.
- In order to get the last location of the user, make use of the Java public class FusedLocationProviderClient. It is actually a location service that combines GPS location and network location to achieve a balance between battery consumption and accuracy. GPS location is used to provide accuracy and network location is used to get location when the user is indoors.
- In conjunction with FusedLocationProviderClient, LocationRequest public class is used to get the last known location. On this LocationRequest object, set a variety of methods such as set the priority of how accurate the location to be or in how many intervals, request of the location is to be made.
- If very high accuracy is required, use PRIORITY_HIGH_ACCURACY as an argument to the setPriority(int) method. For a city level accuracy(low accuracy), use PRIORITY_LOW_POWER.
- Once the LocationRequest object is ready, set it on the FusedLocationProviderClient object to get the final location.
Источник