Today I’m sharing you a working code on how to get the user’s current location in Android. There are many popular apps using this feature such as Google Maps and Facebook. Remember when you checked in a place?
Knowing exactly where your users are located is really cool, but you always have to let them know you are doing it. Asking permission to get user’s location is an ethical way.
One advantage of getting user’s current location is customizing their experience, just like what Twitter does. If you let twitter know your location, it will show top trends or news near you, how cool is that?
I tested this code example without GPS provider which means using internet connection or wifi – it worked. I also tested it outdoors and without internet connection – it also worked. Please note that GPS provider is not working indoors.
When the START button was clicked, our program will get user’s location continually in real time. It will stop when the STOP button was clicked. You can also play with it and change the logic if you just need the latitude and longitude coordinates once.
We will cover the following contents in this post:
1.0 Basic Requirements
2.0 Complete Code
2.1 MainActivity.java
2.2 OnClickListenerButtonStart.java
2.3 OnClickListenerButtonEnd.java
2.4 LocationHelper.java
2.5 AndroidManifest.xml
3.0 Program Output
3.1 On Device
3.2 On Logcat
4.0 Online Resources
1.0 Basic Requirements – Get the User’s Current Location in Android
To make this code run, we will need these five main files. All the description and explanation are provided in their own sections below.
- MainActivity.java
- OnClickListenerButtonStart.java
- OnClickListenerButtonEnd.java
- LocationHelper.java
- AndroidManifest.xml
Your Android device must also have GPS capabilities. If you’re using it outdoors, you must turn it on in your notifications area.
2.0 Complete Code on Getting the User’s Current Location in Android
2.1 MainActivity.java – this is where we initialize the buttons, classes and back press catch.
package com.example.androidgetuserlocation; import com.example.androidgetuserlocation.LocationHelper.LocationResult; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; public class MainActivity extends Activity { final String TAG = "MainActivity.java"; Button buttonStart; Button buttonStop; LocationResult locationResult; LocationHelper locationHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize buttons buttonStart = (Button) findViewById(R.id.buttonStart); buttonStop = (Button) findViewById(R.id.buttonStop); // set button on click listeners buttonStart.setOnClickListener(new OnClickListenerButtonStart()); buttonStop.setOnClickListener(new OnClickListenerButtonEnd()); // to get location updates, initialize LocationResult this.locationResult = new LocationResult(){ @Override public void gotLocation(Location location){ //Got the location! if(location!=null){ double latitude = location.getLatitude(); double longitude = location.getLongitude(); Log.e(TAG, "lat: " + latitude + ", long: " + longitude); // here you can save the latitude and longitude values // maybe in your text file or database }else{ Log.e(TAG, "Location is null."); } } }; // initialize our useful class, this.locationHelper = new LocationHelper(); } // prevent exiting the app using back pressed // so getting user location can run in the background @Override public void onBackPressed() { new AlertDialog.Builder(MainActivity.this) .setTitle("User Location App") .setMessage("This will end the app. Use the home button instead.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).show(); } }
2.2 OnClickListenerButtonStart.java – this is the listener for the “START getting location updates” button. Once clicked, it will start listening to updates given by either GPS or NETWORK provider.
See our LocationHelper for a more detailed explanation on how it gets the user’s current location.
For this simple app to look more responsive to user actions, it will also enable the START button and disable the STOP button.
package com.example.androidgetuserlocation; import android.content.Context; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; public class OnClickListenerButtonStart implements OnClickListener { final String TAG = "OnClickListenerButtonStart.java"; MainActivity mainActivity; Context context; @Override public void onClick(View view) { Log.e(TAG, "Started getting user location."); // to get the context and main activity this.context = view.getContext(); this.mainActivity = ((MainActivity) context); // disable the START button, enable the STOP button mainActivity.buttonStart.setEnabled(false); mainActivity.buttonStop.setEnabled(true); // start listening to location updates mainActivity.locationHelper.getLocation(mainActivity, mainActivity.locationResult); } }
2.3 OnClickListenerButtonEnd.java – this is the listener for the “STOP getting location updates” button. Once clicked, it will stop listening to all ongoing location updates. It will save your device battery consumption, ha!
It will also enable the START button and disable the STOP button.
package com.example.androidgetuserlocation; import android.content.Context; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; public class OnClickListenerButtonEnd implements OnClickListener { final String TAG = "OnClickListenerButtonEnd.java"; MainActivity mainActivity; Context context; @Override public void onClick(View view) { Log.e(TAG, "Ended getting user location."); // to get the context and main activity this.context = view.getContext(); this.mainActivity = ((MainActivity) context); // enable the START button, disable the STOP button mainActivity.buttonStart.setEnabled(true); mainActivity.buttonStop.setEnabled(false); // stop the listener mainActivity.locationHelper.stopGettingLocationUpdates(); } }
2.4 LocationHelper.java – our location helper runs on a very simple logic:
1. First, it tries to detect if any of the providers are enabled – is it the GPS or Network provider?
2. If there’s any provider enabled, it starts the location listener and timer. If after 20 seconds and no values were returned, it will return a null value.
3. If no values were returned, it will still try to get location updates.
package com.example.androidgetuserlocation; import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; public class LocationHelper { final String TAG = "LocationHelper.java"; Timer timer1; LocationManager lm; LocationResult locationResult; boolean gps_enabled = false; boolean network_enabled = false; public boolean getLocation(Context context, LocationResult result) { // I use LocationResult callback class to pass location value from // LocationHelper to user code. locationResult = result; if (lm == null) { lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); } // exceptions will be thrown if provider is not permitted. try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception e) { e.printStackTrace(); } try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception e) { e.printStackTrace(); } // don't start listeners if no provider is enabled if (!gps_enabled && !network_enabled) { return false; } // if gps is enabled, get location updates if (gps_enabled) { Log.e(TAG, "gps_enabled, requesting updates."); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps); } // if network is enabled, get location updates if (network_enabled) { Log.e(TAG, "network_enabled, requesting updates."); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork); } // the timer timer1 = new Timer(); timer1.schedule(new GetLastLocation(), 20000); return true; } LocationListener locationListenerGps = new LocationListener() { public void onLocationChanged(Location location) { // gave a location, cancel the timer timer1.cancel(); // put the location value locationResult.gotLocation(location); // if you want to stop listening to gps location updates, un-comment the code below // lm.removeUpdates(this); // lm.removeUpdates(locationListenerNetwork); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; LocationListener locationListenerNetwork = new LocationListener() { public void onLocationChanged(Location location) { // gave a location, cancel the timer timer1.cancel(); // put the location value locationResult.gotLocation(location); // if you want to stop listening to network location updates, un-comment the code below // lm.removeUpdates(this); // lm.removeUpdates(locationListenerGps); } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } }; // stop listening to location updates public void stopGettingLocationUpdates(){ try{ lm.removeUpdates(locationListenerGps); lm.removeUpdates(locationListenerNetwork); } catch (Exception e) { e.printStackTrace(); } } class GetLastLocation extends TimerTask { @Override public void run() { // In my case, I do not return the last known location, so I DO NOT remove the updates, just return a location value of null // or else, if you need the opposite un-comment the comment below /* lm.removeUpdates(locationListenerGps); lm.removeUpdates(locationListenerNetwork); Location net_loc = null, gps_loc = null; if (gps_enabled){ gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (network_enabled){ net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } // if there are both values use the latest one if (gps_loc != null && net_loc != null) { if (gps_loc.getTime() > net_loc.getTime()){ locationResult.gotLocation(gps_loc); }else{ locationResult.gotLocation(net_loc); } return; } if (gps_loc != null) { locationResult.gotLocation(gps_loc); return; } if (net_loc != null) { locationResult.gotLocation(net_loc); return; } */ locationResult.gotLocation(null); } } public static abstract class LocationResult { public abstract void gotLocation(Location location); } }
2.5 AndroidManifest.xml – this is where the needed permissions are stated.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidgetuserlocation" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.androidgetuserlocation.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
3.0 Program Ouput
Now this is another good part, seeing your code working and run without errors. We’ll have two output for our code which are the “device” and “logcat” output. See them below.
3.1 On Device
Our program provides a simple user interface to be tested.
3.2 On Logcat
The internal notes, latitude and longitude location update values were seen in our logcat.
4.0 Online Resources
What is the simplest and most robust way to get the user’s current location in Android?
Location Strategies
Retrieving the Current Location
3 responses to “How To Get the User’s Current Location in Android? – GPS Example Help”
Its great code to finding current location. It is better thing if the location is on MAP.
your stuff is fantastic.
Hello @abhaykorat:disqus, I’m glad you appreciate this post. I’ll try to work on your idea of putting the location on the map, thanks! In the meantime you can search about Android google maps api or mapview or something…
Hello @ninjazhai:disqus, this is a great code for finding the location through gps but through network provider, im not able get any results.