Google maps api not placing marker at fine location - java

My code is supposed to find out the users location and place a marker on the map upon entering the application. My location value always equals null, and never receives a value.
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "AYO",
"Whats good yo");
CustomPinpoint custom = new CustomPinpoint(d, CampusMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
} else {
Toast.makeText(CampusMap.this, "Couldn't get provider",
Toast.LENGTH_SHORT).show();
}
}

I've had a relatively similar issue with a GPS RPG I was working on and here are some things I noticed:
Firstly, it can take a while for your location to initially be found, which would cause that issue since you're only checking if the location is null.
You may also want to make sure the device's location services are actually enabled before doing anything:
private boolean doLocationsCheck(){
if(!checkLocationEnabled()){
final CharSequence[] items = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Location must be enabled to play this game! Would you like to enable it now?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
final int i = item;
runOnUiThread(new Runnable() {
public void run() {
if(i == 0){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
quit();
}
else{
quit();
}
}
});
}
}).show();
AlertDialog alert = builder.create();
return false;
}
else {
return true;
}
}
private boolean checkLocationEnabled(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER) || service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return enabled;
}
After I've made sure the providers are available I setup a connection like so:
private void setupLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(final Location location) {
runOnUiThread(new Runnable() {
public void run() {
mLocation = location;
//Log.d(TAG, "Latitude: " + location.getLatitude() + " - Longitude: " + location.getLongitude());
saveLocation();
}
});
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Can set to GPS or network, whichever is available
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The location is then set in a global variable whenever it's updated, and then saved to the preferences. This way, in the event that the providers are enabled, but are taking a while to retrieve the location, the user can still continue to use the application with their last known location that the app stored (does not apply to the first time the program is run).
I know I left out a lot there, but I figured it wasn't really necessary since it was either self-explanatory or already explained in a previous answer.
Cheers~

/*
* getting the best location using the location manager
* Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1000 Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1
*/
LocationManager mLocation;
private String mBestProvider;
// in your onCreate() do the following
mLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mBestProvider = mLocation.getBestProvider(criteria, false);
Location location = mLocation.getLastKnownLocation(mBestProvider);
mLocation.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Constants.MINIMUM_TIME_BETWEEN_UPDATES,
Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListenerManager()
);
// and use the following locationListener inner class
private class LocationListenerManager implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MapViewActivity.this, message, Toast.LENGTH_LONG).show();
Log.v("poiint=====", ""+message);
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapViewActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}

You have to initialize the locationlistener in the onstartActivity before on create so that it location obtain the location value before onCreate.

Related

Get current user location

I'm trying to get current user location but on some devices it works, but on some im stuck waiting for the location.
Here is my code:
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// TODO
Log.v("--", "get address 121");
Main.this.location = location;
getAddress();
locationManager.removeUpdates(mLocationListener);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.v("--", "provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.v("--", "provider disabled");
}
};
public void putExtra() {
Intent intent = new Intent(this, Settings.class);
intent.putExtra("timesobj", times);
startActivity(intent);
}
/**
* Get current/last known location and display city, country name and update
* calculations
* */
public void getAddress() {
Log.v("--", "get address 1");
boolean isGPSProviderEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("--", "get address 31 " + isGPSProviderEnabled + " gps - "
+ isConnectedToNetwork());
if (isGPSProviderEnabled || network_enabled) {
Log.v("--", "get address 2");
Criteria c = new Criteria();
Log.v("--", "provider " + locationManager.getBestProvider(c, true));
location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(c, false));
if (location == null) {
Log.v("--", "get address 6");
locationManager.requestLocationUpdates(
locationManager.getBestProvider(c, false), 1000, 100,
mLocationListener);
} else {
Log.v("--", "get address 3");
if (isConnectedToNetwork()) {
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
com.myapp.utils.Geocoder geocoder = new com.myapp.utils.Geocoder(
Main.this);
GeocoderModel geocoderModel = geocoder
.getFromLocation(
location.getLatitude(),
location.getLongitude(), 5);
city = geocoderModel.getCity();
country = geocoderModel.getCountry();
prefs.edit().putString(Constants.CITY, city)
.apply();
Log.v("--", "get address 4");
} catch (IOException e) {
Log.v("--", "get address 11");
e.printStackTrace();
} catch (LimitExceededException e) {
Log.v("--", "get address 12");
e.printStackTrace();
}
return null;
};
protected void onPostExecute(Void result) {
prefs.edit().putString(Constants.COUNTRY, country)
.apply();
prefs.edit().putString(Constants.CITY, city)
.apply();
populateList(location);
};
}.execute();
} else {
city = prefs.getString(Constants.CITY,
getString(R.string.app_name));
Log.v("--", "get address 33 " + location.getLatitude());
populateList(location);
}
}
} else {
Log.v("--", "get address 5");
startGpsEnableDialog();
}
}
and here is the Log that i have:
V/-- ( 5498): get address 1
V/-- ( 5498): get address 31 true gps - true
V/-- ( 5498): get address 2
V/-- ( 5498): provider gp
V/-- ( 5498): get address 6
Can someone help me what can be wrong in this code, and tell me how can I get the user location correctly?
Thanks!
Try to change the line
locationManager.getBestProvider(c, false)
to
locationManager.getBestProvider(c, true)
As stated here, "enabledOnly - if true then only a provider that is currently enabled is returned". You might get back a provider which is not enabled.
One more thing, you seem to be using Criteria, I usually not using it but from looking at your code it looks like you don't do much with it. I suggest you take another look at it. I found a code sample here which might help you.
private void startLocationStuff(){
locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locListener=new MyLocationListener();
final Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
bestProvider=locManager.getBestProvider(criteria,true);
}
You might want to consider using the Location manager without Criteria like this.
The answer was adding this line of code:
locationManager.requestSingleUpdate(locationManager.getBestProvider(c, true), mLocationListener, Looper.myLooper());
I think your code is not that good and main too . Is there a better way .
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.v7.app.AlertDialog;
import android.util.Log;
/**
* Created by moodless3 2017
*/
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 = 1000; // 1000 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2; // 2 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;
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 latitude/longitude 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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#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;
}
}

android getLastKnownLocation() return always return null

I am creating an app that only checks for location when user clicks a button.
here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {
}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
the location service on the device is enabled.
Thanks very much!
getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.
try this pls
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});

Location Manager- function does'nt select provider

My app needs a location and when GPS provider is ON, everything working correctly = I'm getting my location. Unfortunately, when GPS is off my app can't reach Network provider even if it's on and I don't have a clue why.
After this, there's news on the screen Disabled provider Network (In this time network is avalible) and my app crashes.
Code:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);;
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField = "Location not available";
longitudeField = "Location not available";
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider,
400, 1, this);
needGPS = true;
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
if (needGPS == false || starttime == 0)
locationManager.removeUpdates(this);
}
protected void onStop() {
super.onPause();
if (needGPS == false || starttime == 0)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField = (String.valueOf(lat));
longitudeField = (String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
Why Network provider is disabled every time, even when network on my Galaxy SII is ON?
It can be a permission problem.
Open AndroidMaifest.xml and make sure you have
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Android requestLocationUpdates doesn't call never to onLocationChanged in some terminals

I'm working on an app that uses the network location, but i've recived some users feedback that says that they never pass this block of code, i'm assuming that the problem is that location changed is never called, but it only happens in a few diveces, and i cant force the failure in mine.
Is there any chance to solve it or control it? showing a toast saying that is unable to find location, will work for me...
I know that if the user reboot his phone, the location will work, but that it's not a solution for the users
I left the code right here...
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
Location net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
final LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
// SOME STUFF
myTask task = new myTask();
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
} else {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
I've tried with the next idea, i think it could work, at least to get a location and not keep the user waiting.
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
LocationListener locationListenerNetwork = null;
// Constructor
class MyThread implements Runnable {
LocationListener locationListenerNetwork;
public MyThread(LocationListener lln) {
locationListenerNetwork = lln;
}
public void run() {
}
}
final Handler myHandler = new Handler();
//Here's a runnable/handler combo
final Runnable MyRunnable = new MyThread(locationListenerNetwork)
{
#Override
public void run() {
if (locationListenerNetwork != null)
lm.removeUpdates(locationListenerNetwork);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
else
{
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
}
};
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
myHandler.removeCallbacks(MyRunnable);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
myHandler.postDelayed(MyRunnable, 10 * 1000);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0,locationListenerNetwork);
} else {
// MORE STUFF
opinions?

GPS Android - get positioning only once

Is there a way to access the GPS once instead of having a looper that constantly checks for location updates?
In my scenario all I'm interested in is finding the current co-ordinates and not a continuous connection with the GPS satellite. Does anyone have any ideas how this can be done? Thanks in advance.
Dont use the getLastKnownLocation because that could be returning null or old data.
This code Only fetches the location once a button is pressed and not every time. People use to leave the location listener listen in every instance and that kills the battery life so Use the code snippet I have posted by doing lots of research:
// get the text view and buttons from the xml layout
Button button = (Button) findViewById(R.id.btnGetLocation);
final TextView latitude = (TextView) findViewById(R.id.textview4);
final TextView longitude = (TextView) findViewById(R.id.textview5);
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mlocation = location;
Log.d("Location Changes", location.toString());
latitude.setText(String.valueOf(location.getLatitude()));
longitude.setText(String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Status Changed", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Provider Enabled", provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Provider Disabled", provider);
}
};
// Now first make a criteria with your requirements
// this is done to save the battery life of the device
// there are various other other criteria you can search for..
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
// Now create a location manager
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// This is the Best And IMPORTANT part
final Looper looper = null;
// Now whenever the button is clicked fetch the location one time
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestSingleUpdate(criteria, locationListener, looper);
}
});
First check if the last know location is recent. If not, I believe you must to set up onLocationChanged listener, but once you get your first valid location you can always stop the stream of updates.
Addition
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}

Categories

Resources