Skip to main content

Get Current Location using GPS/Network Provider in Android

Hello to all,

 Today I will teach you that how can we get current location.

 In android’s new SDK tools, LocationManager class does not give any network provider’s status. It always gives null value. Still it works in some of the android devices rarely. So that’s why I include code for both network provider and gps provider for getting current location.

 Create one service class name LocationFinder and implements it LocationListener.

 All the code which is related to Location, is doing in that service class and from MainActivity, call its method through its instance in onResume() method.

 The reason you know, why its called in onResume(), because when you enable GPS and come back in activity, then its again check Location’s status.

 In the code, if GPS not enable, I show settings alert pop-up, to go settings menu. When you enable GPS, you will get current location after 2–3 seconds. If not, come again to activity and surely get location.

 Make sure, must add persmissions:
<uses-permission
android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<uses-permission
android:name=”android.permission.ACCESS_FINE_LOCATION”/> 
LocationFinder.java
package com.droidbyme.currentlocation;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
public class LocationFinder extends Service implements LocationListener {
Context context;
boolean isGPSEnabled = false;
// flag for network status
 boolean isNetworkEnabled = false;
// flag for GPS status
 boolean canGetLocation = false;
Location location; // location
 double latitude; // latitude
 double longitude; // longitude
// 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 = 200 * 10 * 1; // 2 seconds
// Declaring a Location Manager
 protected LocationManager locationManager;
public LocationFinder(Context context) {
 this.context = context;
 getLocation();
 }
@Override
 public void onLocationChanged(Location location) {
}
@Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
 public void onProviderEnabled(String provider) {
}
@Override
 public void onProviderDisabled(String provider) {
}
@Nullable
 @Override
 public IBinder onBind(Intent intent) {
 return null;
 }
public Location getLocation() {
 try {
 locationManager = (LocationManager) context
 .getSystemService(LOCATION_SERVICE);
// getting GPS status
 isGPSEnabled = locationManager
 .isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
 isNetworkEnabled = locationManager
 .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
 // no network provider is enabled
 // Log.e(“Network-GPS”, “Disable”);
 } else {
 this.canGetLocation = true;
 // First get location from Network Provider
 if (isNetworkEnabled) {
 locationManager.requestLocationUpdates(
 LocationManager.NETWORK_PROVIDER,
 MIN_TIME_BW_UPDATES,
 MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
 // Log.e(“Network”, “Network”);
 if (locationManager != null) {
 location = locationManager
 .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
 if (location != null) {
 latitude = location.getLatitude();
 longitude = location.getLongitude();
 }
 }
 } else
 // if GPS Enabled get lat/long using GPS Services
 if (isGPSEnabled) {
 if (location == null) {
 locationManager.requestLocationUpdates(
 LocationManager.GPS_PROVIDER,
 MIN_TIME_BW_UPDATES,
 MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
 //Log.e(“GPS Enabled”, “GPS Enabled”);
 if (locationManager != null) {
 location = locationManager
 .getLastKnownLocation(LocationManager.GPS_PROVIDER);
 if (location != null) {
 latitude = location.getLatitude();
 longitude = location.getLongitude();
 }
 }
 }
 }
 }
} catch (Exception e) {
 e.printStackTrace();
 }
return location;
 }
public double getLatitude() {
 if (location != null) {
 latitude = location.getLatitude();
 }
 return latitude;
 }
public double getLongitude() {
 if (location != null) {
 longitude = location.getLongitude();
 }
 return longitude;
 }
public boolean canGetLocation() {
 return this.canGetLocation;
 }
public void showSettingsAlert() {
 AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
 alertDialog.setTitle(“GPS settings”);
 alertDialog.setMessage(“GPS is not enabled. Do you want to go to settings menu?”);
alertDialog.setPositiveButton(“Settings”, new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {
 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
 context.startActivity(intent);
 }
 });
alertDialog.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {
 dialog.cancel();
 }
 });
alertDialog.show();
 }
} 
Do as follow where you want to get location:
LocationFinder finder;
double longitude = 0.0, latitude = 0.0;
finder = new LocationFinder(this);
if (finder.canGetLocation()) {
 latitude = finder.getLatitude();
 longitude = finder.getLongitude();
 Toast.makeText(this, “lat-lng “ + latitude + “ — “ + longitude, Toast.LENGTH_LONG).show();
} else {
 finder.showSettingsAlert();
} 

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App § ...

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap th...