I want to find the longitude and latitude of my current location, but I keep get NULL.
double lat = loc.getLatitude(); //Cause the result is null, so can't know longitude and latitude
double lng = loc.getLongitude();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider); //result is null!
This is the code to get the GPS status. It works fine:
public void onGpsStatusChanged(int event) { // get the GPS statue
LocationManager locationManager = (LocationManager) GpsActivity.this.getSystemService(Context.LOCATION_SERVICE);
GpsStatus status = locationManager.getGpsStatus(null);
String satelliteInfo = updateGpsStatus(event, status);
myTextView.setText(satelliteInfo);//work fine ,searched satellite:16
}
};
private String updateGpsStatus(int event, GpsStatus status) {
StringBuilder sb2 = new StringBuilder("");
if (status == null) {
sb2.append("searched satellite number" +0);
} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
int maxSatellites = status.getMaxSatellites();
Iterator<GpsSatellite> it = status.getSatellites().iterator();
numSatelliteList.clear();
int count = 0;
while (it.hasNext() && count <= maxSatellites) {
GpsSatellite s = it.next();
numSatelliteList.add(s);
count++;
}
sb2.append("searched satellite number:" + numSatelliteList.size());
}
return sb2.toString();
}
getLastKnownLocation() only returns a recent GPS fix, if available. You need to implement a LocationListener and use LocationManager#requestLocationUpdates() to fetch a new location.
Basic implementation:
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) {
// Do something with the recent location fix
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
}
}
// etc..
}
Related
Hello all i know this question is too old and there are many of them but none of the solution is working for me. I am fetching latitude and longitude programmaticaly i tried below code but what is happening is for GPS every time i am getting LastKnownLocation = null also my GPS is enabled on my device, i tried this code on different devices where on some of them i am able to get latitude and longitude from GPS but for most of them it is showing null. I don't know why this code is failing for most of the cases, if any one of you know anything about this or any better way of doing it then please tell me i have spent almost a week digging what's wrong in the above code but nothing help me out.
UPDATE- Is google's FusedLocationApi free or there is limited requests per day ??
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isGPSEnabled) {
Log.d("gps", "gpsenabled");
if (location == null) {
Log.d("gps", "location is null");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
}
if (isNetworkEnabled) {
Log.d("gps", "networkenabled");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
//
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Log.d("gps", "bestProvider: " + bestProvider);
Location location = lm.getLastKnownLocation(bestProvider);
Log.d("gps", "lat: " + location.getLatitude() + ", lon: " + location.getLongitude());
//
}
} catch (Exception e) {
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
latitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to setttings menu ?");
alertDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
latitude = getLatitude();
longitude = getLongitude();
Log.d("gps", "onLocationChanged");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
How do i get longitude longitude of my current phone location using Google maps v2?
I use this method to zoom on my device place:
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
Now how do i get the coordinates?
I know this method to get an area:
double left = vr.latLngBounds.southwest.longitude;
double top = vr.latLngBounds.northeast.latitude; ...
You can get the center Lat and Lng values from google maps via this code
LatLng latLng = map.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
The Google Maps API location has listeners, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new
GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = gMap.addMarker(new MarkerOptions().position(loc));
if(gMap != null){
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
gMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
try this code.
Use This:
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Location location;
private void getMyCurrentLocation() {
Double MyLat = null, MyLong = null;
String CityName = "";
String StateName = "";
String CountryName = "";
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
try {
gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
// if(!gps_enabled && !network_enabled)
// return false;
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
}
if (gps_enabled) {
location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled && location == null) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locListener);
}
if (network_enabled && location == null) {
location = locManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
MyLat = location.getLatitude();
MyLong = location.getLongitude();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
MyLat, MyLong), 15));
} else {
Location loc = getLastKnownLocation(this);
if (loc != null) {
MyLat = loc.getLatitude();
MyLong = loc.getLongitude();
}
}
locManager.removeUpdates(locListener); // removes the periodic updates
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public static Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager) context
.getSystemService("location");
List list = locationmanager.getAllProviders();
boolean i = false;
Iterator iterator = list.iterator();
do {
if (!iterator.hasNext())
break;
String s = (String) iterator.next();
if (i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if (location1 == null)
continue;
if (location != null) {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if (f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if (l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}
my app should display the distance and location in real time when the user walked, but there are errors with my output.
the distance did not start immediately but when it start it increase a lot until it slows down a bit.
the red marker and blue dot should be together according to one example I've seen but they are separate in my app. both of them point my current location right?
both red marker and blue dot jumps around in a short time that i was not moving that is away from my true location. which i believe lead to the inaccuracy of the distance as well.
please see my output for more details
java code
public class MainActivity extends FragmentActivity implements LocationListener{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double speed = 1.6;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0;
TextView distanceText;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 3000; //in milliseconds
boolean startDistance = false;
boolean firstTime = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distanceText=(TextView)findViewById(R.id.Distance);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startDistance = true;
// lat3 = location.getLatitude();
// lon3 = location.getLongitude();
}
});
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
//Display current location in textview
//latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
//lat3 = location.getLatitude();
//lon3 = location.getLongitude();
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
Toast.makeText(MainActivity.this, "Getting map",
Toast.LENGTH_LONG).show();
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
onLocationChanged(myLocation);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
System.out.println("speed " + myLocation.getSpeed());
// if(myLocation.getSpeed() > speed)
// {
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distanceText.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
startDistance=true;
//}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}}
there seem to be no way to solve my error.i was recommeded to use location.getSpeed but it returns 0.
public void getUserLocation() {
Location location;
TextView lon = (TextView) findViewById(R.id.textView2);
TextView lat = (TextView) findViewById(R.id.textView3);
boolean GpsEnable = false, NetworkEnabled = false;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// String locationProvider = LocationManager.GPS_PROVIDER;
GpsEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
NetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// locationManager.requestLocationUpdates(locationProvider,0,0,locationListner);
if (!GpsEnable && !NetworkEnabled) {
Toast.makeText(getBaseContext(), "No Provider Availabe",
Toast.LENGTH_SHORT);
} else {
if (NetworkEnabled)
Toast.makeText(getBaseContext(), "Network Provider Available",
Toast.LENGTH_SHORT);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
if (GpsEnable) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
}
}
}
}
I had done both with GPS and network provider.. I want to know how we get exact current location in Google maps? Is there any way or algorithm by which i can get longitude and latitude of my location using internally Google maps?
Thanks in Advance
I have Followed this Tutorial for Fast Update and Initial SetUp for GoogleMap v2
Initial Setup Here
Alternative for LocationUpdate
Hope this could help...:)
public void retriveLocation(){
try {
String locCtx = Context.LOCATION_SERVICE;
LocationManager locationmanager = (LocationManager) context.getSystemService(locCtx);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationmanager.getBestProvider(criteria, true);
locationmanager.requestLocationUpdates(provider, 0, 0, this);
} catch (Exception e) {
}
}
Hope this code can be useful for retrieving fast location updates.
Here is the code that I basically use to get a constant location signal using Google Play Services.
public class MyActivity
extends
Activity
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener
{
private LocationClient locClient;
private LocationRequest locRequest;
// Flag that indicates if a request is underway.
private boolean servicesAvailable = false;
#Override
protected void onCreate( Bundle savedInstanceState )
{
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
servicesAvailable = true;
} else {
servicesAvailable = false;
}
if(locClient == null) {
locClient = new LocationClient(this, this, this);
}
if(!locClient.isConnected() || !locClient.isConnecting())
{
locClient.connect();
}
// Create the LocationRequest object
locRequest = LocationRequest.create();
// Use high accuracy
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locRequest.setInterval(INTERVAL);
locRequest.setFastestInterval(INTERVAL);
}
#Override
public void onLocationChanged( Location location )
{
// DO SOMETHING WITH THE LOCATION
}
#Override
public void onConnectionFailed( ConnectionResult arg0 )
{
}
#Override
public void onConnected( Bundle arg0 )
{
// Request location updates using static settings
locClient.requestLocationUpdates(locRequest, this);
}
#Override
public void onDisconnected()
{
if(servicesAvailable && locClient != null) {
//
// It looks like after a time out of like 90 minutes the activity
// gets destroyed and in this case the locClient is disconnected and
// calling removeLocationUpdates() throws an exception in this case.
//
if (locClient.isConnected()) {
locClient.removeLocationUpdates(this);
}
locClient = null;
}
}
}
This is the crux of it anyway and I culled this from other sources so I can't really claim it but there it is.
I am using this code. but getting null in longitude and latitude.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Take a look at this tutorial: A Deep Dive Into Location
Basically, if you want to get the approximate location using the last known location, you should iterate through all the possible providers with a loop like this:
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
You can use the LocationManager. See the example:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
And place it in Manisfest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
did you added
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Permission to manifest file
Try This
public class LocationDemo extends Activity implements LocationListener {
private static final String TAG = "LocationDemo";
private static final String[] S = { "Out of Service",
"Temporarily Unavailable", "Available" };
private TextView output;
private LocationManager locationManager;
private String bestProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the output UI
output = (TextView) findViewById(R.id.output);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// List all providers:
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
printProvider(provider);
}
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
output.append("\n\nBEST Provider:\n");
printProvider(bestProvider);
output.append("\n\nLocations (starting with last known):");
Location location = locationManager.getLastKnownLocation(bestProvider);
printLocation(location);
}
/** Register for the updates when Activity is in foreground */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
}
/** Stop the updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
printLocation(location);
}
public void onProviderDisabled(String provider) {
// let okProvider be bestProvider
// re-register for updates
output.append("\n\nProvider Disabled: " + provider);
}
public void onProviderEnabled(String provider) {
// is provider better than bestProvider?
// is yes, bestProvider = provider
output.append("\n\nProvider Enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
output.append("\n\nProvider Status Changed: " + provider + ", Status="
+ S[status] + ", Extras=" + extras);
}
private void printProvider(String provider) {
LocationProvider info = locationManager.getProvider(provider);
output.append(info.toString() + "\n\n");
}
private void printLocation(Location location) {
if (location == null)
output.append("\nLocation[unknown]\n\n");
else
output.append("\n\n" + location.toString());
}
}
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="#+id/output" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
implementation 'com.google.android.gms:play-services-location:11.6.0'
public class LocationExample Eextends AppCompatActivity implements LocationListener {
double latitude, longitude;
LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getLocation()
}
void getLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//GlobalToast.toastMessage(this, "please provide location permission.");
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 400, this);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 400, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("location", "change");
Log.d("latitude", String.valueOf(latitude));
Log.d("longitude", String.valueOf(longitude));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getApplicationContext(), "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
}