Receive GPS Information in Android? - android

I used to receive the GPS information of the code is as follows. The app error is a real phone. I think the problem of the application have to wait for Gps to receive it. How can I do this?
public class Main extends Activity {
TextView text;
Location currentLocation;
double latitude;
double longitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude=location.getLatitude();
longitude=location.getLongitude();
addressText.setText("Latitude: "+latitude+" \n"+"Longitude: "+longitude);
void updateLocation(Location location){
currentLocation = location;
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
}

I believe the official guide explains this quite well. Please take a look there: http://developer.android.com/guide/topics/location/obtaining-user-location.html

This will return null if there no last know location for the GPS.
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
You need to wait until the GSP has got a location fix for it to give you a location by calling onLocationChanged. You can add a GPS status listener to find out when this occurs.
In onCreate add:
locationManager.addGpsStatusListener(locationListener);
Add this method to locationListener:
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.d("GPSStatus", "GPS First Fix");
break;
case GpsStatus.GPS_EVENT_STARTED:
Log.d("GPSStatus", "GPS Started");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.d("GPSStatus", "GPS Stopped");
break;
}
}
You should also check if GPS is enabled before requesting location updates.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))

Related

How to get the new latitude and longitude cordinates from android

How i am getting location details:
AppLocationService appLocationService = new AppLocationService(getApplicationContext());
Location nwLocation= appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
nwLocation.getLatitude();
nwLocation.getLongitude();
What is happening since my code has llast known location .... its giving me the last location that was updated say now its evening. its giving me the location updated during morning
What i want:: how can i make a fresh network request to get the current location at my position
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 0;
private static final long MIN_TIME_FOR_UPDATE = 0;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
Your code is registering to receive location updates and also returns the last known location. What happens is expected because you didn't wait to receive an updated one.
Once the method "onLocationChanged" was called by the system you'll have the new one. You can then send a broadcast from the service.
You are trying to get the current location in a synchronous mode which is not possible as it takes some time to lookup the updated one.
The primary reason why you aren't getting updated location information quickly is that you're relying on the NETWORK_PROVIDER.
You should instead use this
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
How to call Explicitly onLocationChanged
public void locationlist()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
50, 0, this);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {}
if(location == null)
{
}
else{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
}
now call the method locationlist where you want like in a timer.
Use onLocationChanged method and get the longitude and latitude from the parametr location
Code:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = new Location(location);
latitude=mCurrentLocation .getLatitude();
longitude=mCurrentLocation .getLongitude();
}

Android Location Services Not Updating requestLocationUpdates

I have a simple class GPSListener which gets the GPS coordinates:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
Then trying to make use of this class in my activity, I simply invoke the class in my onCreate() function in my activity:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
But whenever I run the application, lat and lon in my activity are always zero. I'm not quite sure how to get around this issue.
When logging:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
It returns the correct latitude and longitude, it just takes a second or two after the activity starts.
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
Just returns 0.0 for both. I was under the impression that .requestLocationUpdates would pass the value to lat and lon before the if statement is executed. How can I accomplish this?
You are using public static field for latitude, longitude.
Please change it to non static and using setter, getter with instant object:
lat = mlocListener.getLatitude();
lon = mlocListener.getLongitude();
Google updated its location handling logic. It is now easier to listen location updates with fused location provider. You can implement your location listener in 5 min. Take a look.
Methods for getting the most accurate location
You are listening only gps provider and it is not ready(on waiting for location status) yet and then it does not return any location. Just take a look at fused location provider and write your location listener again.
try this...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
return false;
}
});
user this Handler to get Location
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
#Override
public void run()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
secndLocationListener.onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
}
};
to run this
customHandler.postDelayed(updateTimerThread , 1000);
LocationManager uses the last known location from the cache. The cache is updated when you load google maps. Try this out, go out in the open and check your location. Move to a different location about 200m and check your location again. It will be same as the old one. Now, load google maps, you will notice that you application magically now has the new location.
You need to programmatically kick that cache to the latest location. The only way to do that is
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});

Why can't I get the location by the NETWORK_PROVIDER as follows?

It is very simple.
But I see nothing appears on the logcat.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_selection);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("MapSelectionActivity", longitude + " " + latitude);
} else {
Log.d("MapSelectionActivity", "location unavailable");
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
I am sure my phone is connected to a wifi access point, which enables the phone to access the internet.
First change the line below:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
To:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
Like it's said here:
public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
...
minTime minimum time interval between location updates, in milliseconds
...
EDIT
I found this tutorial here, which has a simpler usage:
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, this.locationListener);
private final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location locFromGps) {
// called when the listener is notified with a location update from the GPS
}
#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) {
// called when the status of the GPS provider changes
}
}

Find my location don't work (android 2.2)

I tried to implement the code found in this link location find
The truth is I want to get my location using network or GPS, ( I tested it on Network)
private Location getCurrentLocation(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
}
return lastKnownLocation;
}
How to return the result:
myLocation = getCurrentLocation();
if(myLocation != null)
{
mLatitude = myLocation.getLatitude();
mLongitude = myLocation.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}else {
mLatitude = 36.859502;
mLongitude = 10.168097;
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);}
This wasn't the only code i tried and i dont found any result on a android 2.2 phone.
Any idea about how can i fix it
i check most of the tutorials on the net!!
First check whether did you add the following permissions or not.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
The second thing is that you should give some time to locate location info.You can do that using timer task or posDelayed.
private Location getCurrentLocation(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
t.cancel();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation;
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
this.cancel();
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
return lastKnownLocation;
}
},30000);
}
it will give you results after 30seconds.
After a long research, I found my pleasur Here :)
Hope this will help someone.

In ANDROID, How to get a current position and tracking in map using GPS without giving any location in a program?

I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<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"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)

Categories

Resources