Android app find location

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.

Источник

How to get and use location data in your Android app

Using Location in your app has incredible potential in making your app seem intelligent to end users. With location data, your app can predict a user’s potential actions, recommend actions, or perform actions in the background without user interaction.

For this article, we shall discuss integrating location updates into an Android app, with a focus on fetching the latitude and longitude of a given Location only. It is worth pointing out that Location can (and does) contain much more than just latitude and longitude values. It can also have values for the bearing, altitude and velocity of the device.

Preparation

Before your app can receive any location data, you must request location permissions. There are two location permissions, ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION. We use ACCESS_FINE_LOCATION to indicate that we want to receive as precise a location as possible. To request this permission, add the following to your app manifest:

We also need to select which of the location providers we want to use to get the location data. There are currently three providers:

  • GPS_PROVIDER: The most accurate method, which uses the built-in GPS receiver of the device. GPS is a system of satellites in orbit, that provides location information from almost anywhere on earth. It can sometimes take a while to get a GPS location fix (generally faster when the device is outdoors).
  • NETWORK_PROVIDER: This method determines a device’s location using data collected from the surrounding cell towers and WiFi access points. While it is not as accurate as the GPS method, it provides a quite adequate representation of the device’s location.
  • PASSIVE_PROVIDER: This provider is special, in that it indicates that your app doesn’t want to actually initiate a location fix, but uses the location updates received by other applications/services. In other words, the passive provider will use location data provided by either the GPS or NETWORK providers. You can find out what provider your passive provider actually used with the returned Location’s getProvider() method. This provides the greatest battery savings.
Читайте также:  Как найти аирподс через андроид если потерял правый наушник

Layout

For our app, we are going to fetch location data using the GPS provider, the NETWORK provider, and also by asking the device to decide which is the best available provider that meets a given set of criteria. Our layout has three identical segments, each of which contains:

  • A title for the section, such as GPS LOCATION
  • A Button to resume and pause location updates for the section/provider
  • Longitude Value
  • Latitude Value

The code snippet for the GPS section, from our layout/activity_main.xml file is shown below

MainActivity

It is possible that the user has their device Location settings turned off. Before requesting location information, we should check that Location services are enabled. Polling for location data with the settings turned off will return null. To check if Location is enabled, we implement a method, called isLocationEnabled(), shown below:

We simply ask the LocationManager if either the GPS_PROVIDER or the NETWORK_PROVIDER is available. In the case where the user has Location turned off, we want to help them get to the Location screen as easily and quickly as possible to turn it on and get back into our app. To do this, we implement the showAlert() method.

The most interesting line in the snippet above is within the setPositiveButton() method. We start an activity using the Settings.ACTION_LOCATION_SOURCE_SETTINGS intent, so that when the user clicks on the button, they are taken to the Location Settings screen.

Getting location updates

To get GPS and Network location updates, we use one of the LocationManager’s requestLocationUpdates() methods. Our preferred is requestLocationUpdates(String provider, int updateTime, int updateDistance, LocationListener listener). updateTime refers to the frequency with which we require updates, while updateDistance refers to the distance covered before we require an update. Note that updateTime simply specifies the minimum time period before we require a new update. This means that the actual time between two updates can be more than updateTime, but won’t be less.
A very important point to consider is that Location polling uses more battery power. If your app doesn’t require location updates when in the background, consider stopping updates using one of the removeUpdates() methods. In the code snippet below, we stop/start location updates in response to clicking on the relevant Button.

For both NETWORK_PROVIDER and PASSIVE_PROVIDER, simply replace GPS_PROVIDER above with your desired provider.

In the case where you just want to pick the best available provider, there is a LocationManager method, getBestProvider() that allows you do exactly that. You specify some Criteria to be used in selecting which provider is best, and the LocationManager provides you with whichever it determines is the best fit. Here is a sample code, and it’s what we use to select a provider:

Using the above code and Criteria, the best provider will be GPS_PROVIDER, where both GPS and NETWORK are available. However if the GPS is turned off, the NETWORK_PROVIDER will be chosen and returned as the best provider.

LocationListener

The LocationListener is an interface for receiving Location updates from the LocationManager. It has four methods

  • onLocationChanged() – called whenever there is an update from the LocationManager.
  • onStatusChanged() – called when the provider status changes, for example it becomes available after a period of inactivity
  • onProviderDisabled() – called when the user disables the provider. You might want to alert the user in this case that your app functionality will be reduced
  • onProviderEnabled() – called when the user enables the provider

We implement only the onLocationChanged() method for this sample, but in a production app, you will most likely want to perform an appropriate action for each situation.

Android Developer Newsletter

Conclusion

The complete source code is available on github, for use (or misuse) as you see fit. Just be mindful of the following:

  • Integrating location tracking in your apps drains the battery.
  • Google recommends apps request updates every 5 minutes (5 * 60 * 1000 milliseconds). You might need faster updates if your app is in the foreground (fitness/distance tracker).
  • Users can have location turned off. You should have a plan for when location settings is turned off.

Have fun building Android apps, and watch out for our upcoming tutorial where we make use of Android device location data and web APIs to build something even more fun and challenging.

Источник

Get Current Location in Android

This android tutorial is to help learn location based service in android platform. Knowing the current location in an android mobile will pave the way for developing many innovative Android apps to solve peoples daily problem. For developing location aware application in android, it needs location providers. There are two types of location providers,

  1. GPS Location Provider
  2. Network Location Provider
Читайте также:  Android кто запускает процесс

Any one of the above providers is enough to get current location of the user or user’s device. But, it is recommended to use both providers as they both have different advantages. Because, GPS provider will take time to get location at indoor area. And, the Network Location Provider will not get location when the network connectivity is poor.

Network Location Provider vs GPS Location Provider

  • Network Location provider is comparatively faster than the GPS provider in providing the location co-ordinates.
  • GPS provider may be very very slow in in-door locations and will drain the mobile battery.
  • Network location provider depends on the cell tower and will return our nearest tower location.
  • GPS location provider, will give our location accurately.

Steps to get location in Android

  1. Provide permissions in manifest file for receiving location update
  2. Create LocationManager instance as reference to the location service
  3. Request location from LocationManager
  4. Receive location update from LocationListener on change of location

Provide permissions for receiving location update

To access current location information through location providers, we need to set permissions with android manifest file.

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app. But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of network provider.

Create LocationManager instance as reference to the location service

For any background Android Service, we need to get reference for using it. Similarly, location service reference will be created using getSystemService() method. This reference will be added with the newly created LocationManager instance as follows.

Request current location from LocationManager

After creating the location service reference, location updates are requested using requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance and the LocationListener object over which the location to be updated.

Receive location update from LocationListener on change of location

LocationListener will be notified based on the distance interval specified or the number seconds.

Sample Android App: Current Location Finder

This example provides current location update using GPS provider. Entire Android app code is as follows,

XML files for layout and android manifest are as shown below

Android Output

Note: If you are running this Android app with emulator, you need to send the latitude and longitude explicitly for the emulator.

How to send latitude and longitude to android emulator

  • Open DDMS perspective in Eclipse (Window -> Open Perspective)
  • Select your emulator device
  • Select the tab named emulator control
  • In ‘Location Controls’ panel, ‘Manual’ tab, give the Longitude and Latitude as input and ‘Send’.

Comments on «Get Current Location in Android»

nice tutorial sir………..

I am a java developer but not a Android developer. I would like to develop one simple contact save application in android. Could you please publish step by step development procedure for contact book application with sqlite db interaction.

What are all requirement to run anroid applicatio

Very nice article. Steps are nicely explained. Thank you Sir

Hi,
How can i scan barcodes in android application!

yes u can use barcode scan u will find source code for barcode scan check it in github repository once i used zxing(a barcode scanner Engine)

[…] we studied about how to get current geographic location using an android application. That Android app will return latitude and longitude pair to represent current location. Instead of […]

Does this app need any type of internet .

I run the above code.but only hello world is displayed.no location data.Please specify the code for activity main.xml to display the location

Simple and Efficient..

i am new to android ,i tried the same but when i run it shows me “unfortunately app has stopped working” please help me fix this.

Very nice tutorial.Please tell me how can we use these coordinates to locate this position in the map .thank you

First you need to display the map fragment (https://javapapers.com/android/show-map-in-android/), then you need to tile these coordinates on top of it by using location service / activity.

I will post a tutorial for this exact topic very soon.

hi.
its working fine when im using emulator,but it is showing nothing when im uing it in my phone.
just hello world is outputed on the screen.

Hi,
How can i get output in phone instead of emulator because it works in emulator.

i am new to android ,i tried the same but when i run it shows me “unfortunately app has stopped working” please help me fix this

thanks alot for helping by this tutorial..
can u tell me hopw to find the direction and KMS using android google maps

I’m new to android as well and was getting the same error. What solved it was that I tried it on device and not the emulator. The emulator kept giving me error even after sending values through DDMS.

second mistake i made was i changed the name of the package and forgot to change the names in manifest. Just make sure you are not doing the same.

Worked instantly.. Thanks for the tutorial..

how to get date and time from internet in android

Very good tutorial …

Hi,
The latitude and longitude is shown, can you add the direction to the latitude and longitude like

Latitude 37.42 North
Longitude 122.56 East

Because i needed this for astrology app

Thanks Joe,for the post and for GPS Location Provider is works perfectly.

how to develop a music player stand alone application in java……?

Читайте также:  Прога для читов андроид

very good tutorial…thanks sir

its working fine in emulator kindly intimate how to display in tab

Have you posted any tutorial for network based on network location service yet?

Please give URL,

very simple dear
1-install eclipse.
2-After debug the program u will the .apk file
inside Bin folder.
3-Copy the .apk file and put inside ur mobile and run it…

dear Joe when i install apk file in Phone only
hello world message is display not lat n long find

i an new in android apps please help and suggest how to call .NET web service in this with post and get method

I think you are testing code by emulator. If yes, you need to set lattitude and longtitude manually. Its also said by author at the end of this tutorial. Please look at that and then try. Its running good for me.

great job amazing work simple easy yet effective

Nice one.
But This one is not working inside the room.we need the display the current location using network provider.

Thanks, great tutorial, best i found and works like a charm.
Can you publish one explaning GoogleMaps ?

hi , i manually added langitute and logitute .but nothing showing on my emulator..
it says only
latitute=Location not available
longitude=Location not available

This code is not working inside the room.we need the display the current location using network provider.

Great tutorial. I keep having the same problem with certain apps I write – in that they work on the emulator, but give an error on my cell phone.

App starts up then suddenly gives the message “Unfortunately, GPSapp has stopped”

Any ideas would be greatly appreciated

Galaxy S4 cell, 4.2.2

Apologies – I see this question has been raised a few times before. I have tried the suggestions above (eg make sure package name is same in program and manifest etc) but still no joy. Thanks Bryn

There can be numerous reasons to a crash. Best way to find the reason is to get the LogCat logs when it crashes. Plug the phone in USB and set it as target device. Then launch the app in phone and you can get the logs on this error.

all are incredible !

For anyone who shows “Hello World” on the mobile phone instead current location change MainActivity.java to following:

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener <
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
protected Context context;
protected boolean gps_enabled, network_enabled;
TextView txtLat;

@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (gps_enabled) <
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
> else if (network_enabled) <
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
>;
>

@Override
public void onLocationChanged(Location location) <
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText(“Latitude:” + location.getLatitude() + “, Longitude:”
+ location.getLongitude());
>

@Override
public void onProviderDisabled(String provider) <
Log.d(“Latitude”, “disable”);
>

@Override
public void onProviderEnabled(String provider) <
Log.d(“Latitude”, “enable”);
>

@Override
public void onStatusChanged(String provider, int status, Bundle extras) <
Log.d(“Latitude”, “status”);
>
>

In my code, onLocationChanged() method is not getting called while I am running my app on mobile. What may be the reason behind it?

How to send latitude and longitude to android emulator

Open DDMS perspective in Eclipse (Window -> Open Perspective)
Select your emulator device
Select the tab named emulator control
In ‘Location Controls’ panel, ‘Manual’ tab, give the Longitude and Latitude as input and ‘Send’.

For this steps we simple load a .kml file to emulator that will take a automatically from the LOCATION CONTOLS…

Thanks for a nice tutorial.Kindly help me on how to serve the obtained coordinates(latitudes&longitudes) to MySQL database.

Thank you sir…
this is very important to me. Pleas carry on your tutorials ahead.

I have seen some applications being able to retrieve the VLR Global title , something like the Node Number you are latched on , for example in Jordan it will be something like 96279123456 , but from the API i am not able to get to that level , any idea how could that have been done ?

Can anyone please help me on automatic storage of the obtained coordinates (latitude &longitude…from this tutorial)in mySQL database, this should be done without requiring the phone user to press a send button.
May God bless you for your kind assistance.
Happy coding!!

Friends,is there no one who can give a hint on this. Plz your assistance or some links/books to refer to will help me a lot.

I want to find my friend location trough googlemap
So what kind of permission i have to use in my manifest file ,is this possible??

i am working on one friend Find locater .
reply

Sir this code running well in emulator but not in phone device and itz by default shows hello world.. how can i fix it?and as like many people are geeting same problem.. pls gv us proper solution.

Its is really awesome tutorial Thank You 🙂

Sir,
i am using GPS Location find in my application and how to store in sqlite database so i am confuesd please help me sir.

i need source code

[…] said all the above, I just noticed that I have written an Android GPS tutorial already. Though I feel like a buffoon, somehow I have to manage now. Its okay, it will do no harm […]

Источник

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