I am currently writing an app which will access the current location on the press of a button, and print it out. What I have right now is a method which gets the last known location. I have seen in many places that one is to implement a class that gets the location. My current code returns it as a string, but it only gets the location that was last updated by the phone. How can I change this so that when I press the button and call a method that uses this String, it will get the currentLocation rather than the lastLocation?
Thank you so much!
Also, This is my first ever android app, and I only have intermediate knowledge of Java and class implementation.
public String getLocation(){
String userLocation;
try {
LocationManager locMgr = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String userLocator = recentLoc.toString();
userLocation = compressString(userLocator);
//userLocation = recentLoc.toString();
}
catch(Exception e) {
userLocation = "Location failed";
}
return userLocation;
}
I think your GPS is turned off right now. If you turn on your device's location services, it will print out the last location which is near by you. If it won't work, you must implement LocationListener class to your activity. Like at this link.
Try with this code:
LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {
#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
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
double lat=location.getLatitude();
double lng=location.getLongitude();
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);//or LocationManager.NETWORK_PROVIDER
}
Try this in onClick method
private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
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) {}
};
locationManager
.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
}
Related
I am creating application for showing Gps location .I need to show location in every 1min.can i use timer.if so kindly provide me timer code.
You cannot use timer to get location updates. There already is a way to get updates of user's current location.
You should call the requestLocationUpdates() method to get the updates of the lastKnownLocation.
The method is like,
LocationManager mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100, this);
This will get Last Known Location updates after 1000 milliseconds and 100 meters.
And to get the latitude longitude,
Location location;
if (mLocMgr != null) {
location = mLocMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println(latitude+" "+longitude);
}
}
Refer Location Manager in documentation
As per your query I understand that you would like to request a location update every 1 minute and you have written a handler for it. Try the following code which worked for me.
LocationManager mlocManager;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
//paste this in your handler or timer
{
if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestSingleUpdate(
LocationManager.NETWORK_PROVIDER, mlocListener, null);
} else if (mlocManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
mlocListener, null);
}
}
//this the class to get the location.
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
//you may store these values where ever required.
Double latitude = location.getLatitude();
Double latitude = location.getLongitude();
} catch (Exception e) {
e.printStackTrace();
}
}
#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
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
I have been doing android programing for the last 3 months but I'm having a hard time on this problem.
My task: I want my device to be able to get its current location (latitude and longitude) and pass it to another class where I have a bitmap. The bitmap is a Map I drew myself. So does anyone know a simple way to pass latitude and longitude coordinates to another class?
Note: once I get the coordinates and pass them to the other class I know how to draw on my bitmap. I'm working with eclipse and java btw. And I wish to do this without using phonegap.
EDIT : I have used the following code (where i found it in a tutorial) and when i use it i can view the location. The problem is i do not know how he gets the location exactly. So can anybody pls explain to me how can i use this code to pass the location to another class?
Many thanks in advance!
package org.mh00217.SilineSnap;
public class LocationActivity extends MapActivity implements LocationListener { //<1>
private static final String TAG = "LocationActivity";
LocationManager locationManager; //<2>
Geocoder geocoder; //<3>
TextView locationText;
MapView map;
MapController mapController; //<4>
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
map = (MapView)this.findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
mapController = map.getController(); //<4>
mapController.setZoom(16);
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE); //<2>
geocoder = new Geocoder(this); //<3>
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //<5>
if (location != null) {
Log.d(TAG, location.toString());
this.onLocationChanged(location); //<6>
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); //<7>
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this); //<8>
}
#Override
public void onLocationChanged(Location location) { //<9>
Log.d(TAG, "onLocationChanged with location " + location.toString());
String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(),
location.getLongitude(), location.getAltitude(), location.getBearing());
this.locationText.setText(text);
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
for (Address address : addresses) {
this.locationText.append("\n" + address.getAddressLine(0));
}
int latitude = (int)(location.getLatitude() * 1000000);
int longitude = (int)(location.getLongitude() * 1000000);
GeoPoint point = new GeoPoint(latitude,longitude);
mapController.animateTo(point); //<11>
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
From the GPS receiver, you get a Location-object. It implements the Parcelable-interface.
If you want to pass this object to another Activity, you can add it to a Bundle:
Intent i = new Intent(...);
i.putExtra("Location", location); // The object.
startActivity(i);
I have an application written in HTML5 and wrapped in PhoneGap.
I have a map on an application and I want to find a user's location by GPS.
I tried it the following way:
In JS I have a function that changes the position of the marker:
function GPS(lat, lon) {
alert('Now U move');
var CurrentPosition = new google.maps.LatLng(lat, lon);
markerMyLoc.setPosition(CurrentPosition);
}
In Java, I have functions that care on location and send the JS function:
public class MainActivity extends DroidGap {
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/XXX.html", 10000);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
}
}
GPSLocationListener class:
public class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GPScls MyGPS= new GPScls();
MyGPS.GPS(location.getLatitude(),location.getLongitude());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
GPScls class:
public class GPScls extends DroidGap {
public void GPS(double latitude,double longitude) {
super.loadUrl("javascript:GPS("+latitude+","+longitude+")");
}
}
the alert: alert('Now U move'); Not shown, can anyone help me solve this?
I realized that, I did not go enough to return an answer from GPS
Look at the following question:
Is the function onLocationChanged called every movement of Android device?
I have the following code:
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
and in my MainActivity
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Now, all I want is to receive the current position of the device ONCE to the MainActivity class (get altitude and longitude variables to use later in the application).
A. how do I stop receiving the location after a single time? The function lm.removeUpdates(listener) can only be called in the MainActivity class.
B. basically the same. How do I connect between the MyLocationListener class and the MainActivity one?
Sorry, I'm a newbie to Android and Java development.
And thanks!
You may use the following sample code:
public class LocationGetter {
private final Context context;
private Location location = null;
private final Cordinate gotLocationLock = new Cordinate();
private final LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
synchronized (gotLocationLock) {
LocationGetter.this.location = location;
gotLocationLock.notifyAll();
Looper.myLooper().quit();
}
}
};
public LocationGetter(Context context) {
if (context == null)
throw new IllegalArgumentException("context == null");
this.context = context;
}
public void getLocation(int maxWaitingTime, int updateTimeout) {
try {
final int updateTimeoutPar = updateTimeout;
synchronized (gotLocationLock) {
new Thread() {
public void run() {
Looper.prepare();
LocationResolver locationResolver = new LocationResolver();
locationResolver.prepare();
locationResolver.getLocation(context, locationResult, updateTimeoutPar);
Looper.loop();
}
}.start();
gotLocationLock.wait(maxWaitingTime);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
gteAddress ();
}
public double getLatitude() {
return location.getLatitude();
}
public double getLongitude() {
return location.getLongitude();
}
In your activity use:
_locationGetter=new LocationGetter(context);
_locationGetter.getLocation(200000000, 10000000);
_locationGetter.getLongitude();
_locationGetter.getLatitude();
You can also use LocationManager.removeUpdates after obtining the coordinates (and possibly checking if the coordinates are sufficient for your needs):
#Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
lm.removeUpdates(this);
}
How to get the current Latitude and Longitude in android2.3.3?
I try to Follow this but I can't run programs.
My code
LatView = (TextView)findViewById(R.id.LatText);
LngView = (TextView)findViewById(R.id.LngText);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
In android manifest I put this.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Please help.
Thanks.
This is what i have in my application to find the device current location, it works fine:
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
public static double myLocationLatitude;
public static double myLocationLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
Log.d("best provider", best);
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
//may be some intent here
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 1, this);
}
private void dumpLocation(Location l) {
if (l == null) {
myLocationLatitude = 0.0;
myLocationLongitude = 0.0;
} else {
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String p : providers) {
dumpProviders(p);
}
}
private void dumpProviders(String s) {
LocationProvider info = mgr.getProvider(s);
StringBuilder builder = new StringBuilder();
builder.append("name: ").append(info.getName());
}
}
Here MyLocationLatitude and MyLocationLongitude gives the values of lat and long you needed.
You need to check if the last location is null, if it is then you ask the GPS provider for a new location like so:
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 if it is less than two minutes old
}
else {
// Request a new location if necessary
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
public void onLocationChanged(Location location) {
if (location != null) {
// Do something withthe current location
// If you only want one location update un-comment this line
//mLocationManager.removeUpdates(this);
}
}
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}