How to get coordinates from GPS in Android? - android

This is not working:
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
After this code, it goes to catch statement.
Another issue is that the solving statement is giving me error. A red line under it.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Hint for the above error is that in the Android Studio:
Call requires permission which may be rejected by user: code should
explicitly check to see if permission is available (with
checkPermission) or explicitly handle a potential
SecurityException
This is my whole code to get gps coordinates from Android phone.
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) {
Toast.makeText(getApplicationContext(), "1111", Toast.LENGTH_LONG).show();
// no network provider is enabled
} else {
this.canGetLocation = true;
Toast.makeText(getApplicationContext(), "2222", Toast.LENGTH_LONG).show();
// First get location from Network Provider
if (isNetworkEnabled) {
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;
}

In according to Requesting Permission :
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
There are 2 difference:
System permissions are divided into two categories, normal and dangerous:
Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically.
Dangerous permissions can give the app access to the user's confidential data. If your app lists a normal permission in its manifest, the system grants the permission automatically. If you list a dangerous permission, the user has to explicitly give approval to your app.
So if you are using API 23 you must check explicit permission if you would access to location service so add this:
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//DO OP WITH LOCATION SERVICE
}
I suggest you to check also if app is running on device with API >= 23 with this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//DO CHECK PERMISSION
}

You should add following line to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

please include your manifest code too ,have you added those permissions ?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Related

Trying to get location with cell tower but still returns null

What I am trying to do is to get location from user. First it tries to get location through GPS and checks whether location is available. If not then it it tries to get through Network tower. When GPS is turned on it is working fine. But when I turn off GPS it's not getting location using network provider
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = manager.getBestProvider(new Criteria(), false);
Log.i("ITEMSET best", provider);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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;
}
Log.i("ITEMSET provider", provider);
location = manager.getLastKnownLocation(provider);
Log.i("ITEMSET netLoc", location + "");
if(location==null) {
provider = LocationManager.NETWORK_PROVIDER;
location = manager.getLastKnownLocation(provider);
Log.i("ITEMSET netLoc", location + "qqq");
}
Log.i("ITEMSET current", provider);
Log.i("ITEMSET location", location + "");
Location was initially null because GPS wasn't turned on. But then changed provider to network provider. But location still null
Check Whether Network is Enabled or not
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
then:
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000,10, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
You should use GoogleApiClient to get your location. Please visit this post

locationManager.getLastKnownLocation() always returns null on new xperia X performance

I'm creating an app that needs to know the users coarse location and on every other phone I've tested this works fine but on my xperia X performance, getLastKnownLocation() always returns null without exception.
This code works on other devices and the gps works on my phone with other apps.
public boolean startLocationManager() {
// Check for permission to use Fine Location
if (ContextCompat.checkSelfPermission(mActivity,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
String providerInfo = null;
// Check if Network provider is enabled
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerInfo = LocationManager.NETWORK_PROVIDER;
}
else{
showSettingsAlert();
}
// Application can use GPS or Network Provider
if (providerInfo != null) {
locationManager.requestLocationUpdates(
providerInfo,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location != null){
isEnabled = true;
}
else{
Toast.makeText(mActivity, R.string.location_is_turned_off, Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Can't connect to LocationManager", e);
}
}
return isEnabled;
}
I've given the app the right permissions and I still can't get anything but null from getLastKnownLocation().
I don't know if it's of any help but heres some phone info:
Phone info
if (providerInfo != null) {
locationManager.requestLocationUpdates(
providerInfo,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(
LocationManager.NETWORK_PROVIDER);
}
It's not guaranteed to get location from getLastKnownLocation, because it retrieves previously cached location if any. You have to wait until onLocationChanged callback is fired

Android LocationManager network provider returns null

I wanted to get my GPS coordinates using Android App. I started developing, and I can get GPS coordinates, but they are not accurate. I wanted to use NETWORK_PROVIDER, but the Location by this provider is always null. More interesting, isProvicerEnabled returns true.
I used example from this thread (best answer)
enter link description here
private void _getLocation() {
// Get the location manager
try {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Location location = null;
double latitude = -1;
double longitude = -1;
// 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 {
if (isNetworkEnabled) {
showToast("network");
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
0, 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
else if (isGPSEnabled) {
showToast("gps");
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
0, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
showToast("" + latitude + longitude);
} catch (Exception e) {
e.printStackTrace();
}
I have all the permissions in manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I know the code is dirty, but for now it's only for testing. Do I miss something? I found similar examples in many places, and it seems pretty straight, so I am a little confused.
My phone works ok, GPS and network works fine. For example Google Maps application I have works well. Any suggestions?
Please do NOT use this code. It's bad. It has a lot of errors. Also, getLastKnownLocation will return null if it doesn't have a location yet. Which it always will if nobody on the phone is using requestUpdates.
Your code is taken from a class that was posted on a very old thread on here called GPSTracker. I've been trying to kill that code for months- it causes far more problems than it helps. If you want better example code, try http://gabesechansoftware.com/location-tracking/ which is a blog post I wrote about how bad that code is. It will show you the correct way to do it, and explains some of what's wrong with that code.

Android - getting GPS coordinates on service thread

I've been working on an application that tracks a users GPS coordinates and intermittently sends updates to my server. This is done in a thread within a service. Most of the time the first reading will be accurate but when moving the GPS is not updating. I think this is because the LocationManager takes some time to warm up. The location setting on the device will also affect the outcome (Device only, high accuracy), sometimes resulting with 0.0 being returned. Is there a simple solution that will allow it enough time before the values are decided upon?
Service thread:
new Thread() {
public void run() {
// prepare looper
Looper.prepare();
// send text messages
String numbersList = helper.getNumbers();
if (numbersList != "") {
String numbersArray[] = numbersList.split(", ");
for (int i = 0; i < numbersArray.length; i++) {
sendSMS(numbersArray[i], incident_id);
}
}
// run until told otherwise
while (active == true) {
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
accuracy = gps.getAccuracy();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
GPS Tracker Class:
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 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();
}
}
}
}
else if(isNetworkEnabled) {
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();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
Your first location always is the last known location (locationManager.getLastKnownLocation(...)). This location may be relativly old, for example the last fix of the GPS before it was turned off or before you entered a building. Its accurracy in relation to your current location is more or less random (unless you did not move or left the building using the same door).
If the GPS was turned off or the satellites were not visible for a while (e.g. inside a building) the hardware will need some time to get a fix on the current location. This is the delay you are seeing. Afterwards your location listener (not shown above) will get updates from the GPS.

Google Maps - Location keeps jumping between my real location and 0.6 miles away (Random place)

I've got Google Maps v2 running on my app, using a service to get the users location. Problem is the location keeps changing. It shows my real location for a bit, then jumps to a random location that I've never been to before.
I'm check GPS/Network lat/lng via the service and calling them in my maps class, where I then animate the camera to move to my location. I don't really know what's wrong, or where to start with this one.
Does anyone know what sort of problem this is? It's baffling to me.
I don't really know what code to post. The accuracy of the location via network is 1121m where as the accuracy of the location via GPS is around 31. I'm using a LocationListener and in the onLocationChanged is says it's using my network location, suddenly the accuracy improves, to 29m, then it suddenly goes back up to 1121m. This happens about every minute or so. Very odd behaviour. With GPS enabled, shouldn't that be the preferred choice anyway? Is there a way to set it to my preferred choice once it gets a fix?
My service gets it's information like this:
public Location getLocation() {
Log.i("getLocation", "Get location called");
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 and GPS is off.
Log.d("NOT ENABLED", "PASSIVE PROVIDER");
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
loc = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("PASSIVE_LOCATION", "Location: "+loc.toString());
}
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
Log.d("Network", "Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("NETWORK_LOCATION", "Location: "+loc.toString());
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("GPS_LOCATION", "Location: "+loc.toString());
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
//check provider & accuracy
Log.d("PROVIDER", loc.getProvider());
Log.d("ACCURACY", Float.toString(loc.getAccuracy()));
return loc;
If anyone could help I would really appreciate it. Thank you in advance.
I think this solved itself. It was jumping between locations simply because of accuracy. Once GPS accuracy was better than network, it started updating via GPS.
I'm also stopping location updates once the accuracy is less than 30 in onLocationChanged so I have a bit more control and don't waste the users battery.

Categories

Resources