If you are developing any location based app, you can make your app more smarter by finding user’s location automatically. For this you need to integrate location modules in your application. You can learn more about location strategies.
In this tutorial, we are going to learn how to get user location using GPS location manager with and without internet.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LocationGPS Demo</string> <string name="location_without_internet">Get Location Without Internet</string> <string name="location_internet">Get Location Using Internet</string> <string name="display_location">Your Location will be displayed here.</string> </resources> |
3. Open AndroidManifest.xml and add ACCESS_FINE_LOCATION (Which includes both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION). Also we have to detect internet connection so we need ACCESS_NETWORK_STATE this permission also.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.locationgps_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- This permission is used to get current location via internet --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- This permission is used to check internet connection --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".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> |
4. Now create a xml layout containing two button and two textview to display location using internet and without internet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:orientation="vertical" android:padding="5dp" > <Button android:id="@+id/get_location_without_internet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center" android:padding="10dp" android:text="@string/location_without_internet" /> <TextView android:id="@+id/show_location_without_internet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="10dp" android:gravity="center" android:text="@string/display_location" android:textColor="#000000" android:textSize="16sp" /> <Button android:id="@+id/get_location_using_internet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center" android:padding="10dp" android:text="@string/location_internet" /> <TextView android:id="@+id/show_location_using_internet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="10dp" android:gravity="center" android:text="@string/display_location" android:textColor="#000000" android:textSize="16sp" /> </LinearLayout> |
5. Create a new java class naming ConnectionDetector.java to detect Internet connection. If you don’t no how to detect internet connection then you can check my tutorial here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.locationgps_demo; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context) { this._context = context; } // This method will return boolean value if internet is there or not public boolean isConnectingToInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) _context .getSystemService(Context.CONNECTIVITY_SERVICE);// Connectivity // manager to // work on // connectivtiy // service NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();// Get // the // network // info if (networkInfo != null && networkInfo.isConnected()) {// Check if // network info // is not null // and it is // connected return true;// Internet is there } else { return false;// No internet } } } |
6. Now, create a new java class naming GPSService.java extending Service also implement this class from LocationListener and add the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class GPSService extends Service implements LocationListener { // saving the context for later use private final Context mContext; // if GPS is enabled boolean isGPSEnabled = false; // if Network is enabled boolean isNetworkEnabled = false; // if Location co-ordinates are available using GPS or Network public boolean isLocationAvailable = false; // Location and co-ordinates coordinates Location mLocation; double mLatitude; double mLongitude; // Minimum time fluctuation for next update (in milliseconds) private static final long TIME = 30000; // Minimum distance fluctuation for next update (in meters) private static final long DISTANCE = 20; // Declaring a Location Manager protected LocationManager mLocationManager; public GPSService(Context context) { this.mContext = context; mLocationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); } |
Add the implementation for the function geoLocation() which was called in the constructor. In this function we’ll get the location from network provider first. If network provider is disabled, then we get the location from GPS provider.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
public Location getLocation() { try { // Getting GPS status isGPSEnabled = mLocationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // If GPS enabled, get latitude/longitude using GPS Services if (isGPSEnabled) { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, TIME, DISTANCE, this); if (mLocationManager != null) { mLocation = mLocationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); isLocationAvailable = true; // setting a flag that // location is available return mLocation; } } } // If we are reaching this part, it means GPS was not able to fetch // any location // Getting network status isNetworkEnabled = mLocationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (isNetworkEnabled) { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this); if (mLocationManager != null) { mLocation = mLocationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); isLocationAvailable = true; // setting a flag that // location is available return mLocation; } } } // If reaching here means, we were not able to get location neither // from GPS not Network, if (!isGPSEnabled) { // so asking user to open GPS askUserToOpenGPS(); } } catch (Exception e) { e.printStackTrace(); } // if reaching here means, location was not available, so setting the // flag as false isLocationAvailable = false; return null; } |
This method will return the complete address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
public String getLocationAddress() { if (isLocationAvailable) { Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); // Get the current location from the input parameter list // Create a list to contain the result address List<Address> addresses = null; try { /* * Return 1 address. */ addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1); } catch (IOException e1) { e1.printStackTrace(); return ("IO Exception trying to get address:" + e1); } catch (IllegalArgumentException e2) { // Error message to post in the log String errorString = "Illegal arguments " + Double.toString(mLatitude) + " , " + Double.toString(mLongitude) + " passed to address service"; e2.printStackTrace(); return errorString; } // If the reverse geocode returned an address if (addresses != null && addresses.size() > 0) { // Get the first address Address address = addresses.get(0); /* * Format the first line of address (if available), city, and * country name. */ String addressText = String.format( "%s, %s, %s", // If there's a street address, add it address.getMaxAddressLineIndex() > 0 ? address .getAddressLine(0) : "", // Locality is usually a city address.getLocality(), // The country of the address address.getCountryName()); // Return the text return addressText; } else { return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it."; } } else { return "Location Not available"; } } |
This methods used to getLongitude, getLatitude and closeGPS.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/** * get latitude * * @return latitude in double */ public double getLatitude() { if (mLocation != null) { mLatitude = mLocation.getLatitude(); } return mLatitude; } /** * get longitude * * @return longitude in double */ public double getLongitude() { if (mLocation != null) { mLongitude = mLocation.getLongitude(); } return mLongitude; } /** * close GPS to save battery */ public void closeGPS() { if (mLocationManager != null) { mLocationManager.removeUpdates(GPSService.this); } } |
If GPS is not enabled then prompt user to enable GPS via this method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * show settings to open GPS */ public void askUserToOpenGPS() { AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title mAlertDialog.setTitle("Location not available, Open GPS?") .setMessage("Activate GPS to use use location services?") .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }) .setNegativeButton("Cancel",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } |
Final Source code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
package com.locationgps_demo; import java.io.IOException; import java.util.List; import java.util.Locale; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; public class GPSService extends Service implements LocationListener { // saving the context for later use private final Context mContext; // if GPS is enabled boolean isGPSEnabled = false; // if Network is enabled boolean isNetworkEnabled = false; // if Location co-ordinates are available using GPS or Network public boolean isLocationAvailable = false; // Location and co-ordinates coordinates Location mLocation; double mLatitude; double mLongitude; // Minimum time fluctuation for next update (in milliseconds) private static final long TIME = 30000; // Minimum distance fluctuation for next update (in meters) private static final long DISTANCE = 20; // Declaring a Location Manager protected LocationManager mLocationManager; public GPSService(Context context) { this.mContext = context; mLocationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); } /** * Returs the Location * * @return Location or null if no location is found */ public Location getLocation() { try { // Getting GPS status isGPSEnabled = mLocationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // If GPS enabled, get latitude/longitude using GPS Services if (isGPSEnabled) { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, TIME, DISTANCE, this); if (mLocationManager != null) { mLocation = mLocationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); isLocationAvailable = true; // setting a flag that // location is available return mLocation; } } } // If we are reaching this part, it means GPS was not able to fetch // any location // Getting network status isNetworkEnabled = mLocationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (isNetworkEnabled) { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this); if (mLocationManager != null) { mLocation = mLocationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); isLocationAvailable = true; // setting a flag that // location is available return mLocation; } } } // If reaching here means, we were not able to get location neither // from GPS not Network, if (!isGPSEnabled) { // so asking user to open GPS askUserToOpenGPS(); } } catch (Exception e) { e.printStackTrace(); } // if reaching here means, location was not available, so setting the // flag as false isLocationAvailable = false; return null; } /** * Gives you complete address of the location * * @return complete address in String */ public String getLocationAddress() { if (isLocationAvailable) { Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); // Get the current location from the input parameter list // Create a list to contain the result address List<Address> addresses = null; try { /* * Return 1 address. */ addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1); } catch (IOException e1) { e1.printStackTrace(); return ("IO Exception trying to get address:" + e1); } catch (IllegalArgumentException e2) { // Error message to post in the log String errorString = "Illegal arguments " + Double.toString(mLatitude) + " , " + Double.toString(mLongitude) + " passed to address service"; e2.printStackTrace(); return errorString; } // If the reverse geocode returned an address if (addresses != null && addresses.size() > 0) { // Get the first address Address address = addresses.get(0); /* * Format the first line of address (if available), city, and * country name. */ String addressText = String.format( "%s, %s, %s", // If there's a street address, add it address.getMaxAddressLineIndex() > 0 ? address .getAddressLine(0) : "", // Locality is usually a city address.getLocality(), // The country of the address address.getCountryName()); // Return the text return addressText; } else { return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it."; } } else { return "Location Not available"; } } /** * get latitude * * @return latitude in double */ public double getLatitude() { if (mLocation != null) { mLatitude = mLocation.getLatitude(); } return mLatitude; } /** * get longitude * * @return longitude in double */ public double getLongitude() { if (mLocation != null) { mLongitude = mLocation.getLongitude(); } return mLongitude; } /** * close GPS to save battery */ public void closeGPS() { if (mLocationManager != null) { mLocationManager.removeUpdates(GPSService.this); } } /** * show settings to open GPS */ public void askUserToOpenGPS() { AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title mAlertDialog.setTitle("Location not available, Open GPS?") .setMessage("Activate GPS to use use location services?") .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }) .setNegativeButton("Cancel",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } /** * Updating the location when location changes */ @Override public void onLocationChanged(Location location) { mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } |
7. Now, create a new java class naming GPSLocation.java. This class contains methods like turnOn ,turnOff GPS and getLocation that we will use in our activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
package com.locationgps_demo; import java.util.Iterator; import java.util.List; import java.util.Locale; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.Log; public class GPSLocation { private Context context; private StringBuilder currentLocation = new StringBuilder(); public GPSLocation(Context context) { this.context = context; } /** * Check the type of GPS Provider available at that instance and collect the * location informations * * @Output Latitude and Longitude */ public void turnGPSOn() { try { @SuppressWarnings("deprecation") String provider = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (!provider.contains("gps")) { // if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); context.sendBroadcast(poke); } } catch (Exception e) { } } // Method to turn off the GPS @SuppressWarnings("deprecation") public void turnGPSOff() { String provider = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (provider.contains("gps")) { // if gps is enabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); context.sendBroadcast(poke); } } public String getMyCurrentLocation() { LocationManager locManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); LocationListener locListener = new MyLocationListener(); try { gps_enabled = locManager .isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { } try { network_enabled = locManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { } // don't start listeners if no provider is enabled // if(!gps_enabled && !network_enabled) // return false; if (gps_enabled) { locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); } if (gps_enabled) { location = locManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (network_enabled && location == null) { locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener); } if (network_enabled && location == null) { location = locManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if (location != null) { MyLat = location.getLatitude(); MyLong = location.getLongitude(); currentLocation.append("Latitude : " + MyLat + "nLongitude : " + MyLong); } else { Location loc = getLastKnownLocation(context); if (loc != null) { MyLat = loc.getLatitude(); MyLong = loc.getLongitude(); } } locManager.removeUpdates(locListener); // removes the periodic updates // from location listener to // //avoid battery drainage. If // you want to get location at // the periodic intervals call // this method using //pending // intent. try { // Getting address from found locations. Geocoder geocoder; List<Address> addresses; geocoder = new Geocoder(context, Locale.getDefault()); addresses = geocoder.getFromLocation(MyLat, MyLong, 1); StateName = addresses.get(0).getAdminArea(); CityName = addresses.get(0).getLocality(); CountryName = addresses.get(0).getCountryName(); currentLocation.append("nState Name : " + StateName + "nCity Name : " + CityName + "nCountry Name : " + CountryName); // you can get more details other than this . like country code, // state code, etc. } catch (Exception e) { e.printStackTrace(); } return currentLocation.toString(); } // Location listener class. to get location. public class MyLocationListener implements LocationListener { public void onLocationChanged(Location location) { if (location != null) { } } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } private boolean gps_enabled = false; private boolean network_enabled = false; Location location; Double MyLat, MyLong; String CityName = "", StateName = "", CountryName = ""; // below method to get the last remembered location. because we don't get // locations all the times .At some instances we are unable to get the // location from GPS. so at that moment it will show us the last stored // location. public static Location getLastKnownLocation(Context context) { Location location = null; LocationManager locationmanager = (LocationManager) context .getSystemService("location"); List<String> list = locationmanager.getAllProviders(); boolean i = false; Iterator<> iterator = list.iterator(); do { if (!iterator.hasNext()) break; String s = (String) iterator.next(); if (i != false && !locationmanager.isProviderEnabled(s)) continue; Location location1 = locationmanager.getLastKnownLocation(s); if (location1 == null) continue; if (location != null) { float f = location.getAccuracy(); float f1 = location1.getAccuracy(); if (f >= f1) { long l = location1.getTime(); long l1 = location.getTime(); if (l - l1 <= 600000L) continue; } } location = location1; i = locationmanager.isProviderEnabled(s); } while (true); return location; } } |
8. The above two classes are used to get location in presence of internet but in absence of internet we have to do something else. I am using this method to get current location in latitude and longitude.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
private void getLocationWithoutInternet() { // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { // The toast will show loaction continuosly as we are requesting // local updates Toast.makeText( getApplicationContext(), location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_SHORT) .show(); } }; // Register the listener with the Location Manager to receive location // updates if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } |
9. Finally come to your MainActivity.java and add the following code. In this activity we are getting current location via internet and without internet. While getting location through internet we have to check first if internet is present or not. So for this I used ConnectionDetector class to get network status.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
package com.locationgps_demo; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements OnClickListener { private static Button getLocation, getLocation_usingInternet; private static TextView displayLocation, displayInternetLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setListeners(); } // Initialize the views private void init() { getLocation = (Button) findViewById(R.id.get_location_without_internet); getLocation_usingInternet = (Button) findViewById(R.id.get_location_using_internet); displayLocation = (TextView) findViewById(R.id.show_location_without_internet); displayInternetLocation = (TextView) findViewById(R.id.show_location_using_internet); } // Set listeners over both button private void setListeners() { getLocation.setOnClickListener(this); getLocation_usingInternet.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.get_location_using_internet: getLocationUsingInternet(); break; case R.id.get_location_without_internet: getLocationWithoutInternet(); break; } } // Method that will return location in longitude, latitude, city, state, and // country private void getLocationUsingInternet() { boolean isInternetConnected = new ConnectionDetector(MainActivity.this) .isConnectingToInternet(); // Before proceding we have to check if therr is internet connection or // not if (isInternetConnected) { getLocation_usingInternet.setText("Please wait...");// while getting // location // please wait // and disable // the button getLocation_usingInternet.setEnabled(false); new GPSLocation(MainActivity.this).turnGPSOn();// First turn on GPS String getLocation = new GPSLocation(MainActivity.this) .getMyCurrentLocation();// Get current location from // Location class displayInternetLocation.setText(getLocation);// Set location over // textview // Now again change the state of button getLocation_usingInternet.setText(R.string.location_internet); getLocation_usingInternet.setEnabled(true); } else { // If there is no internet connection toast will be displayed Toast.makeText(MainActivity.this, "There is no internet connection.", Toast.LENGTH_SHORT) .show(); } } // Method that will fetch the location in longitude and latitude in absence // of internet private void getLocationWithoutInternet() { // Change the state of button getLocation.setText("Please wait.."); getLocation.setEnabled(false); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { // Display currnet longitude and latitude over textview displayLocation.setText("Latitude : " + location.getLatitude() + "nLongitude : " + location.getLongitude()); // The toast will show loaction continuosly as we are requesting // local updates Toast.makeText( getApplicationContext(), location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_SHORT) .show(); // Now, again change the state of button getLocation.setText(R.string.location_without_internet); getLocation.setEnabled(true); } }; // Register the listener with the Location Manager to receive location // updates if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } @Override protected void onDestroy() { super.onDestroy(); // When activity destroyed we have to turn off GPS new GPSLocation(MainActivity.this).turnGPSOff(); } } |
10. Now, you are all done. If you run your app in emulator you will get longitude and latitude but if you run it over real device you will get proper address (in case of internet).
Thanks.
Subscribe to us and get the latest news.