I want to achieve something which I though was simple enough, but now I end up being a little confused.
I want to get the coordinates of the user in this way
Is there a GPS provider?
If yes, get the coordinates from gps
Else if there is a network provider get them from there
I used both locationManager and onLocationChange(), and the new API with locationClient but I can't get the coordinates from my device's GPS, only from network.
This is the one with the locationManager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use default
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
// new AlertDialog.Builder(v.getContext()).setMessage("Provider " + provider + " has been selected.").show();
onLocationChanged(location);
System.out.println(location.getLatitude());
Intent intent = new Intent(getApplicationContext(),DriveMeActivity.class);
intent.putExtra("monument", monument);
intent.putExtra("latitude", location.getLatitude());
intent.putExtra("longitude",location.getLongitude());
startActivity(intent);
} else {
new AlertDialog.Builder(con).setMessage("Location not available").show();
System.out.println("Location not available");
System.out.println("Location not available");
}
and this is the one with locationClient
GooglePlayServicesUtil.isGooglePlayServicesAvailable(v.getContext())
if(mLocationClient.getLastLocation()!=null)
Toast.makeText(getApplicationContext(),
mLocationClient.getLastLocation().getLongitude()+ "|" +
mLocationClient.getLastLocation().getLatitude() ,
Toast.LENGTH_SHORT).show();
here's the complete code to find the best available provider whether gps or network and show settings menu to enable the location services.
public class DSLVFragmentClicks extends Activity implements LocationListener {
private final int BESTAVAILABLEPROVIDERCODE = 1;
private final int BESTPROVIDERCODE = 2;
LocationManager locationManager;
String bestProvider;
String bestAvailableProvider;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BESTPROVIDERCODE) {
if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestProvider);
}
} else {
if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestAvailableProvider);
}
}
}
public void getLocation(String usedLocationService) {
Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
long updateTime = 0;
float updateDistance = 0;
// finding the current location
locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);
}
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.main);
// set a Criteria specifying things you want from a particular Location Service
Criteria criteria = new Criteria();
criteria.setSpeedRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
criteria.setAltitudeRequired(false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// finding best provider without fulfilling the criteria
bestProvider = locationManager.getBestProvider(criteria, false);
// finding best provider which fulfills the criteria
bestAvailableProvider = locationManager.getBestProvider(criteria, true);
String toastMessage = null;
if (bestProvider == null) {
toastMessage = "NO best Provider Found";
} else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
// show settings menu to start gps or network location service
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
} else {
getLocation(bestAvailableProvider);
}
toastMessage = bestAvailableProvider + " used for getting your current location";
} else {
boolean enabled = locationManager.isProviderEnabled(bestProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTPROVIDERCODE);
} else {
getLocation(bestProvider);
}
toastMessage = bestProvider + " is used to get your current location";
}
Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
// getting the street address from longitute and latitude
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
String addressString = "not found !!";
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder stringBuilder = new StringBuilder();
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
addressString = stringBuilder.toString();
locationManager.removeUpdates(this);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderEnabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderDisabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
I have already explained a lot in comments but if you still don't understand something then feel free to ask.
I hope you are trying it on a device and you have tried it out in open. In most cases You won't get gps coordinates until you step out.
Most probably you don't have the location fix and GPS locationProvider takes time to get the location fix in compare to network location provider.
What can you do is that you can use the last known location fix.
String locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.NETWORK_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
But the further problem is that you might have the old location fix and network provider can provide you better location.
Android has really good documentation on this and sample code to find the best known location.
http://developer.android.com/guide/topics/location/strategies.html
Related
I'm using this code to get the geo-position of the user
public Location getLocation() {
Location location = null;
double lat;
double lng;
try {
LocationManager mLocationManager = (LocationManager) con.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, this);
Log.d("Network", "Network");
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
System.out.println(lat);
}
}
}
//get the location by gps
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
System.out.println(lat);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
An this is what I get:
Network
39.68967
Gps Enabled
(nothing)
I can't understand the reason why Gps is enabled and I still can't get the coordinates from the gps provider
I just finished creating a sample project for understanding the usage of Location Services. I am just posting my code, feel free to use it for your need and understanding the working of Location Services.
public class DSLVFragmentClicks extends Activity implements LocationListener {
private final int BESTAVAILABLEPROVIDERCODE = 1;
private final int BESTPROVIDERCODE = 2;
LocationManager locationManager;
String bestProvider;
String bestAvailableProvider;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BESTPROVIDERCODE) {
if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestProvider);
}
} else {
if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestAvailableProvider);
}
}
}
public void getLocation(String usedLocationService) {
Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
long updateTime = 0;
float updateDistance = 0;
// finding the current location
locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);
}
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.main);
// set a Criteria specifying things you want from a particular Location Service
Criteria criteria = new Criteria();
criteria.setSpeedRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
criteria.setAltitudeRequired(false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// finding best provider without fulfilling the criteria
bestProvider = locationManager.getBestProvider(criteria, false);
// finding best provider which fulfills the criteria
bestAvailableProvider = locationManager.getBestProvider(criteria, true);
String toastMessage = null;
if (bestProvider == null) {
toastMessage = "NO best Provider Found";
} else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
} else {
getLocation(bestAvailableProvider);
}
toastMessage = bestAvailableProvider + " used for getting your current location";
} else {
boolean enabled = locationManager.isProviderEnabled(bestProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTPROVIDERCODE);
} else {
getLocation(bestProvider);
}
toastMessage = bestProvider + " is used to get your current location";
}
Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
// getting the street address from longitute and latitude
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
String addressString = "not found !!";
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder stringBuilder = new StringBuilder();
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
addressString = stringBuilder.toString();
locationManager.removeUpdates(this);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderEnabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderDisabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
If you didn't understand any part of it then feel free to ask.
// Use LocationManager.NETWORK_PROVIDER instead of GPS_PROVIDER.
public Location getLocation(){
try{
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}catch (Exception e) {
e.printStackTrace();
}
if(locationManager != null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
}
return location;
}
i am developing an gps program in that i am getting gps values for every 5 minutes,
and it is working great, but i have to store the values which i get. it has been refreshed for every 5 minutes and i have only one text view so that it deletes the old values when the new one is refreshed.
this is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(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"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
Thank you.
You can store your Textview's value into a file for persistance storage. Study my answer properly, I am adding a file store method in your existing code,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(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"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File("sdcard/gpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to write following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well you have plenty of persistence options, but in this case the best is using SharedPreferences
No one can say for sure without knowing exactly what you need to do with the saved data. ArrayList is a good option if you need to store it temporarily. You can create a new ArrayList then put the value in there at the same time that you use it in setText(). If you want something permanent then you will probably want to store it in a DB or a file. Check out Storage Options
Also, in this case, a good idea may be to store it in an ArrayList temporarily then use that list to transfer them to a file or DB for permanent storage if that's what you want
Another way to store it temporarily, and possibly save somewhere later would be a HashMap. Maybe something in the form of HashMap<String, HashMap<String, String>>. Since we don't know your exact intentions with the data, examples could be endless but maybe this will give you a good starting point so you can decide what will work best for you then you can find many examples all over SO and the Google for your choice
Have started a Location Listener in the main activity and want to share location updates with other classes that are an extension of the main. Have tried several different variations, but nothing seems to get the job done. The toast message shows up with each change in Intent and when the GPS is updated in Eclipse, just need the data. Looking for a little help or a different perspective. Have limited expertise in Android, but believe this can be done in the main activity versus a separate Thread or AsyncTask. Thank you for the help!
Here is the location manager set up in the main.
private void initSystems() {
// Location Manager
LocationManager lm;
String context = Context.LOCATION_SERVICE;
lm = (LocationManager)getSystemService(context);
// Set up Location Manager
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
Provider = lm.getBestProvider(criteria, true);
Location location = lm.getLastKnownLocation(Provider);
updateWithNewLocation(location);
lm.requestLocationUpdates(Provider, 100, 10,locListener);
}
Here is the Listener and Update
private final LocationListener locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
updateWithNewLocation(loc);
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String Provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String Provider){ }
public void onStatusChanged(String Provider, int status, Bundle extras){
Toast.makeText(getApplicationContext(), "onStatusChanged", Toast.LENGTH_SHORT).show();
}
};
private double updateWithNewLocation(Location loc) {
double loc_update = 0;
if (loc != null) {
lat = loc.getLatitude();
lng =- loc.getLongitude();
loc_update = lat+lng;
Toast.makeText(getApplicationContext(), "Lat & Long" + lat + " "+lng, Toast.LENGTH_LONG).show();
Log.d(DEBUG_TAG, "Lat & Long " + lat + " "+lng);
return loc_update;
}
else {
Toast.makeText(getApplicationContext(), "Unable to Obtain GPS Data", Toast.LENGTH_SHORT).show();
Log.d(DEBUG_TAG, "Unable to Obtain GPS Data");
}
return loc_update;
}
I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do I always get a null value?
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);
if (location != null) {
System.out.println("Location is not null!");
lat = (int) (location.getLatitude() *1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
"2nd String");
CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
overlayList.clear();
} else {
System.out.println("Location is null! " + towers);
Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
.show();
}
getLastKnownLocation() uses the location(s) previously found by other applications. if no application has done this, then getLastKnownLocation() will return null.
One thing you can do to your code to have a better chance at getting as last known location- iterate over all of the enabled providers, not just the best provider. For example,
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
If your app can't deal without having a location, and if there's no last known location, you will need to listen for location updates. You can take a look at this class for an example,
https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java
See the method onStartCommand(), where it checks if the network provider is enabled. If not, it uses last known location. If it is enabled, it registers to receive location updates.
if u find current location of devices the use following method in main class
public void find_Location(Context con) {
Log.d("Find Location", "in find_location");
this.con = con;
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) con.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
addr = ConvertPointToLocation(latitude, longitude);
String temp_c = SendToUrl(addr);
}
}
}
And Add User Permission method in your manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Try this this will not give you null current location
class GetLastLocation extends TimerTask {
LocationManager mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;
public GetLastLocation(Handler mLocHandler) {
this.mLocHandler = mLocHandler;
}
#Override
public void run() {
timer.cancel();
mlocManager.removeUpdates(mlocListenerTmp);
Location location = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
{
if (mlocListenerTmp != null) {
mlocManager.removeUpdates(mlocListenerTmp);
}
currentLocation = location;
}
if (location != null) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Log.d("loc", " :" + message);
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Log.d(
"loc",
":No GPS or network signal please fill the location manually!");
location = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLocation = location;
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", false);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
}
}
}
}
call it like this
timer.schedule(new GetLastLocation(mLocHandler), 3000);
and the customLocationclass is as follows
public class CustomLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
currentLocation = loc;
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
Log.d("loc", "onLocationChanged" + Text);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
If you are trying it out in a marshmallow device, try enabling location permission for your app manually.
turn on your GPS by using below method. it helps you to show your current location without any ERROR. call it in onCreate
public void displayLocationSettingsRequest(Context context, int requestCode) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(result1 -> {
final Status status = result1.getStatus();
if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
try {
status.startResolutionForResult((Activity) context, requestCode);
} catch (IntentSender.SendIntentException ignored) {
}
});
If you are getting a null error with your provider list, change...
List<String> providers = mLocationManager.getProviders(true);
to...
List<String> providers = locationManager.getAllProviders();
This worked for me, and make sure that you have the following in your AndroidManifest.xml file...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Have you tried reversing the code? For example, if(location==null) then print that location is null, and else print location is not null. I got that problem once before and that seemed to have fixed it (i don't know why). Try that.
If that doesn't work, perhaps the google maps API is returning the null value, in which case its a problem with the GM-API or with the call method. Any of these could be the problem.
public class LocationtesterActivity extends Activity {
/** Called when the activity is first created. */
LocationManager locManager;
// LocationListener locListener;
Button b;
String provider;
TextView lat, alt, longi;
// Here i am first checking if both GPS and network options are enabled in Lovation and Security Settings or not.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.button1);
lat = (TextView) findViewById(R.id.lattitude);
alt = (TextView) findViewById(R.id.altitude);
longi = (TextView) findViewById(R.id.longitude);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locManager.getBestProvider(criteria, true);
System.out.println("best provider is :" + provider);
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| !locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
System.out.println("in provider enablement");
createGpsDisabledAlert();
}
else {
System.out.println("in location update request");
locManager.requestLocationUpdates(provider, 0, 0,
new MyLocationListener());
}
}
// for displaying the Dialogue Box
// if GPS or network not enabled
// and also taking to location and security screen
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Your GPS or network provider is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable provider",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions() {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gpsOptionsIntent, 5);
}
// //////ends/////
// Code to check whether user enabled GPS and Network provider in settings
// if not then show the dialogue box again
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 5 && resultCode == 0) {
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createGpsDisabledAlert();
// Toast.makeText(this,
// "provider not enabled. Click the button for settings",
// 2000).show();
} else {
Intent i=new Intent(this, LocationtesterActivity.class);
startActivity(i);
Toast.makeText(this, "User has enabled the provider", 1000)
.show();
}
}
}
// Method to display the current location
protected void showCurrentLocation() {
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
lat.setText("" + location.getLatitude());
longi.setText("" + location.getLongitude());
Toast.makeText(LocationtesterActivity.this, message,
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(LocationtesterActivity.this, "no last known location", 1000).show();
}
}
// Inner class for LocationListener
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
System.out.println("in location changed");
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
lat.setText("" + location.getLatitude());
longi.setText("" + location.getLongitude());
// alt.setText("" + location.getAltitude());
Toast.makeText(LocationtesterActivity.this, message,
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LocationtesterActivity.this,
"Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LocationtesterActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LocationtesterActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
I am using the above code to find the User Location.
1.I am getting always GPS as the best provider according to my criteria but that is fine to me.
2.Thing is that why am i not able to get any location values ?
Even with Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); i am not getting any thing.
Please help me in getting the location values.
GPS take some time due to slow and not available inside the building .You just check it outside the building.
And
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); only works if once GPS get any location previously.
Two things,
Have u set "android.permission.ACCESS_FINE_LOCATION" permission in manifest file ??
clear all data of Google map application and then try to load map for get current location on map, If Google map give your current location then your application can fetch current location.
Its good habit to use best criteria for fetching location.
sometimes devices can not read current location. I also face this problem but at that time i check Google Map / Direction application and reset my GPS.