problem in getting gps coordinates in android 2.1(Found Answer) - android

I am having a problem in getting GPS coordinates in 2.1.
The code i am using right now is working well in 1.6 but when i test
this same apk in 1.6 device is showing null values
please help me to find a way to work with 2.1 devices also
Here is my code.
public class GpsLocator {
private static String PROVIDER="gps";
private LocationManager myLocationManager=null;
public GpsLocator(Context context) {
myLocationManager=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void myOnresume() {
myLocationManager.requestLocationUpdates(PROVIDER, 0, 0, onLocationChange);
}
public void myonPause() {
myLocationManager.removeUpdates(onLocationChange);
}
public double getLatitude() {
Location loc=myLocationManager.getLastKnownLocation(PROVIDER);
if (loc==null) {
return(0);
}
return(loc.getLatitude());
}
public double getLongitude() {
Location loc=myLocationManager.getLastKnownLocation(PROVIDER);
if (loc==null) {
return(0);
}
return(loc.getLongitude());
}
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status,Bundle extras) {
// required for interface, not used
}
};
}
in the manifest file i add permission for accessing file they are
<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" />

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};

LocationManager.getLastKnownLocation does not guarantee that it will return a valid location. If a GPS fix hasn't been established yet, it will return null. The only reliable way to get an actual location is to use the LocationListener -interface. I see that you have defined a LocationListener, but aren't using it.
You need to modify your code so that it waits for the first call to onLocationChanged before you try to do anything with the location.

Hi I am also facing same problem in 2.1 after i resolved like this...
it will work for you
myManager = ((LocationManager) ApplicationController.getAppContext()
.getSystemService(Context.LOCATION_SERVICE));
myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1 * 1000, 0.00001f, this);
Follow location changed asy method in tha u will get lat/and long
don't use bundle object over there it wont work instead of that you can use Gps Satellite class for 2.1..

Related

Unable to get GPS Location with Common Code

I have code to get location, which I believe must be working but it doesn't at all:
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Java:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
new MyLocationListener()
);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
System.out.println("location: " + location);
location prints null and the listener never get called at all. Anyone can advise what's wrong? If I open Google Maps, it can return my location anyway.
Note: I am testing with my device
Create Class SingleShotLocationProvider in your utility package or wherever you are fine with below code.
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
public class SingleShotLocationProvider {
public interface LocationCallback {
void onNewLocationAvailable(Location location);
}
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (Utility.checkAndRequestPermissionsForGPS(context)) {
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}, null);
} else {
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}, null);
}
}
}
}
}
Now in you Activity import it like
import com.yourdomain.utils.SingleShotLocationProvider;
Now you can use it like below this is reference to your activity
SingleShotLocationProvider.requestSingleUpdate(this,
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
}
});
You will receive location in first attempt just make sure GPS is on and set to high accuracy.And in manifest you have given necessary permission as like below -
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Try this code. I am using the GPS here to get the latitude and longitude.
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Get Last LOcation" + location.getLatitude()
+ location.getLongitude());
loc.setLatitude(location.getLatitude());
loc.setLongitude(location.getLongitude());
}
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) {
// TODO Auto-generated method stub
if (location.getAccuracy() < 50) {
locationManager.removeUpdates(locationListener);
}
}
};
locationManager.requestLocationUpdates(provider,
INTERVAL_TIME_SECONDS, MIN_DISTANCE_METERS,
locationListener);

other way to get current location in Android

the code below gives a NullPointerException is there any other way of getting current location in Android application
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = location.getLatitude(); //NullPointerException
double longitude = location.getLongitude();
sure you could use the google play services location API:
http://developer.android.com/google/play-services/location.html
but maybe you should look into your problem first... see this question for your null problem:
android getlastknownlocation returns null

Android: how to find total distance covered using GPS when continuously moving?

This is my code. Please tell me y it is not able to calculate the distance.. In this code res is a long variable which is supposed to store the total distance covered. This code is supposed to calculate distance based on GPS as soon as there is a change in the latitude and longitude..
String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager;
locationManager= (LocationManager)getSystemService(serviceString);
String provider = LocationManager.GPS_PROVIDER;
final Location loc1=locationManager.getLastKnownLocation(provider);
//Location loc1=new Location("");
String netprovider=LocationManager.NETWORK_PROVIDER;
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location loc1)
{
Location loc2=new Location("");
lat2=loc2.getLatitude();
lon2=loc2.getLongitude();
dtvalue.setText(lat1+","+lon1+","+lat2+","+lon2);
Location.distanceBetween(lat1,lon1,lat2,lon2,dist);
res=res+(long)dist[0];
lat1=lat2;
lon1=lon2;
}
public void onProviderDisabled(String provider)
{
// Update application if provider disabled.
}
public void onProviderEnabled(String provider)
{
// Update application if provider enabled.
}
public void onStatusChanged(String provider, int status,
Bundle extras)
{
// Update application if provider hardware status changed.
}
};
locationManager.requestLocationUpdates(provider, 5000, 1, myLocationListener);
locationManager.requestLocationUpdates(netprovider, 5000, 1, myLocationListener);
The problem that you are defining an empty location Location loc2=new Location(""); and then using it.
You can define lat1 and lon1 in your class.
public void onLocationChanged(Location loc1)
{
if(lat1 != 0 && long1 != 0) {
Location.distanceBetween(lat1,lon1,loc1.getLatitude(),loc1.getLongitude(),dist);
res+=(long)dist[0];
}
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
}

How to get the current fixed position in emulator?

I'm trying an application that displays the latitude and longitude positions. I tried giving lat. & lon. values using geo fix and even emulator control but I'm not getting the output. Can anyone help me out?
Here's the code and output that i get:
public class LocationTest extends Activity
{
private LocationManager mgr;
private TextView output;
private String best;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
StringBuilder sb = new StringBuilder("Enabled Provider:");
Criteria criteria = new Criteria();
String provider = mgr.getBestProvider(criteria, true);
mgr.requestLocationUpdates(provider, 1000, 0,
new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
});
sb.append("\n").append(provider).append(":");
Location location = mgr.getLastKnownLocation(provider);
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
sb.append(lat).append(",").append(lng);
}
else
{
sb.append("No Location");
}
output.setText(sb);
}
}
Output:
Enabled provider:
gps:No Location
You need to put code in public void onLocationChanged(Location location) {} of your LocationListener. This is where location changes are informed.
getLastKnownLocation() doesn't give you current location, but last known location (which will most likely be null on the emulator).
Use Android SDK's DDMS to signal GPS position. This will call onLocationChanged(). You need a way to preserve the new location in your class (for example adding a Location class object to your Activity).

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