Unable to get location from gps - android

I am trying to create an app which gets latitude and longitude from user's gps this is the class that I am using :-
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
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 = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.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
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return TODO;
Toast.makeText(this,"It's very important that you agree to gps permission, kindly restart the app and accept",Toast.LENGTH_LONG).show();
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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.d("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;
}
when I call this function in MainActivity it never asks for any permissions and also doesn't show any errors this is the function that I am using :-
String getlocurl(){
GPSTracker gps;
gps = new GPSTracker(MainActivity.this);
double latitude = 0;
double longitude = 0;
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
String mapurl = "https://www.google.com/maps/preview/#"+lat+","+lng+","+"8z";
return mapurl;
}
else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
return "error";
}
}
This is the result that I get : "https://www.google.com/maps/preview/#0.0,0.0,8z"
it returns 0.0,0.0 as latitude and longitude, how do I fix this?

Put this on your Manifest file before the application tag:
<uses-permission android:name="android.permission.INTERNET" /> <!-- verify if connected to the internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- verify if connected to any network -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- verify location using GPS, give precise location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- verify location using WiFi and mobile, gives approximate location -->

Related

getLocation() method returning NULL location even when GPS is on

I'm trying to make an application which gives current location to the user if GPS is On and shows an AlertDialog if not and asks for turning On the GPS.But the method returns NULL only either GPS is On or Off... How can I solve it? I've looked for solution here and here but it didn't help.
Below is the getLocation() method that I'm using
public Location getLocation() {
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
Toast.makeText(this,"using gps",Toast.LENGTH_LONG).show();
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) {
Toast.makeText(this,"using network",Toast.LENGTH_LONG).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions((Activity)getBaseContext(), new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_ACCESS_COURSE_LOCATION );
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// return TODO;
}
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) {
Toast.makeText(this,"turn on gps",Toast.LENGTH_LONG).show();
// 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;
}
I have referred the above code from the answer to one of the above mentioned links.

Get user current lat lng after GPS enabled - Android

I have followed this tutorial http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ for showing popup if GPS in not enabled and getting users current location.
And here is the broadcast receiver which listens to the GPS enabled disabled condition
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
gps = new GPSTracker(getActivity());
if(gps.canGetLocation()){
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
Toast.makeText(getActivity(), "GPS Switch", Toast.LENGTH_SHORT).show();
if(gps.getLatitude() != 0 && gps.getLongitude() != 0 ){
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(gps.getLatitude(),gps.getLongitude())) // Sets the center of the map to selected place
.zoom(15) // Sets the zoom
.build(); //
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Toast.makeText(getActivity(), "GPS Switch Lat: "+gps.getLatitude()+" Long: "+gps.getLongitude(), Toast.LENGTH_SHORT).show();
}
} else {
if(!gps.isSettingDialogShown())
gps.showSettingsAlert();
}
}
}
};
When I enable the GPS via settings dialog or from drop down menu. GPSTracker class gets the location service and checks for the user's current location in this code fragment
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.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
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
return location;
}
Problem:
Firstly I don't know why broadcast receiver, receives the action two times and secondly when in normal mode lat lng value in receiver remains zero but in debugging sometimes it returns the value of users current location.
Can you please help what I am doing wrong?
If you don't need to work with Gps and Network Locations separately. I recommend to use FusedLocationProvider. BroadcastReceiver is probably working twice because it works for both gps and network location services

Get String from Location Android

I found a great function which gives me possibility to get Location quickly.
After that i want to display its (longitude and latitude) but it doest work still i get 0.0 / 0.0.
here's code
What should i do if i want display this latitude and longitude mostly I'm interested in function getLastKnownLocation because i want display this data without using GPS or Internet
public class MainActivity extends Activity implements OnClickListener
{
private static final long MIN_TIME_BW_UPDATES = 0;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
public EditText lokalizacja;
public Button pobierz;
private static Context context;
LocationManager locationManager;
// flag for GPS status
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
public static Context getContext()
{
return context;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lokalizacja = (EditText) findViewById(R.id.editText1);
pobierz = (Button) findViewById(R.id.button1);
pobierz.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
getLocation();
}
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
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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, (LocationListener) this);
Log.d("GPS", "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();
}
String napis = String.valueOf(latitude+ "\n" + longitude);
lokalizacja.setText(napis);
return location;
}
}
As flow never enter the else part due the following condition
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
You need to have condition something like this
if (!isGPSEnabled || !isNetworkEnabled) {
// no network provider is enabled
} else {
or first check for GPS and then after network
For the first time, for getting your current location, you want to enable gps or network in your device. After getting lat and lng create a preference and save these values to preference. So make some changes in your getLocation() method.
If gps and network are disable try to return the saved value from preference.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />

Isn't it possible to get coordinate without wifi?

my code is here:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(false);
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
It only get coordinate when I connected to internet.
You can use android GPS service to get Longitute and Latitute too,
add the permission in your AndroidMenifest.xml,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Initialization,
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = 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;
// This is constructor to get System Location services,
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
Checking if GPS managed to fetch the data,
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();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

Android GPS using old locations

Im trying to learn more about location services in android and am attempting to build an app which can locate an Android device and send it's latitude and longitude to a server. I've had everything working as expected for a while, but am still being bothered by a small bug. When I send the command from the server to locate the device the first time, the device returns a recent, but old, location such as a road I drove on the same day.
On the second time the device receives a command from the server to locate the device, the device returns an accurate location.
Here is the relevant code:
LocationTracker.java
public class LocationTracker extends Service implements LocationListener {
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10*1000; //10,000 meters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10000; // 10,000 minutes
//Declaring a Location Manager
protected LocationManager locationManager;
public void fetchLocation(Context context) {
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
new MyAsyncTask().execute(stringLatitude, stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
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
}
else
{
this.canGetLocation = true;
//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.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
//If no GPS, get location from Network Provider
if (isNetworkEnabled && !isGPSEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(LocationTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
Log.i("New Location: ", stringNewLatitude + " " + stringNewLongitude);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public IBinder onBind(Intent intent)
{
return null;
}
Why is my location updating as an old location the first time it tries, and a correct location on the second time?
Also note that I would also like to remove requestLocationUpdates seen here:
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
because it causes a handler on dead thread warning, but when I removed it my device stopped acquiring my location. This may be part of the problem.
I would greatly appreciate any help!
It's because you're using getLastKnownLocation().
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation(String Provider) :
Returns a Location indicating the data from the last known location fix obtained from the given provider.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

Categories

Resources