86581

Unable to get location with gps location provider on android device

Question:

I am developing small location based android application in which I need users current location. I am also updating users current location as soon as some change in location is occurred.My code looks like:

private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LocationManager locationManager; String svcName = Context.LOCATION_SERVICE; locationManager = (LocationManager)getSystemService(svcName); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setSpeedRequired(false); criteria.setCostAllowed(true); String provider = locationManager.getBestProvider(criteria, true); //Location l = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER); Location l = locationManager.getLastKnownLocation(provider); updateWithNewLocation(l); locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); } private void updateWithNewLocation(Location location) { TextView myLocationText; myLocationText = (TextView)findViewById(R.id.myLocationText); String latLongString = "No location found"; if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); latLongString = "Lat:" + lat + "\nLong:" + lng; } myLocationText.setText("Your Current Position is:\n" + latLongString); }

My problem is that when I use provider as network then it's working fine. But when it select gps as provider then it's giving null value. I know for the first time it gives me null value. I also used onLocationChanged method but it's still not giving me proper output. When I open my application it shows me output null value and it also start gps for serching my location. I wait for some time to get updated location but it not giving me valid output. Is there any thing wrong with my code. I am using android device.

Need Help... Thank you...

Answer1:

Have you entered these permission in the manifest?

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_GPS"/>

Answer2:

When You use the Provider as Network, then you get the location immediately as it gets the Location values of nearest Tower of the network provider. But when you use GPS, it takes some time to fetch the current location values. In your case (after seeing code) it is very much clear that you are getting last known location using Network Provider so it gets the location and when use gps provider it takes some time and more importantly if you are in close area, takes more time to get location values through gps provider.

Answer3:

here,system is trying to select best provider according to the criteria you have set

e.g. criteria.setPowerRequirement(Criteria.POWER_LOW);

but GPS provider doesn't fit with the criteria which you have specified. that is why it may not working properly.either change the criteria or if you want to get location updates from GPS provider only then use following code,

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, 10, locationListener);

Answer4:

please use this class for when you use User current loaction

private GPSTracker gps; gps = new GPSTracker(this); if (gps.canGetLocation()) { /*----get Lat and Long---------*/ double lat = gps.getLatitude(); double lon = gps.getLongitude(); String mLatitute = Double.toString(lat); String mLongitute = Double.toString(lon); }

GPTTracker Service:

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 = null; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 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.e("Network", "Network Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.e("GPS", "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/wifi enabled * * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog On pressing Settings button will * lauch 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 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 cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } public void onLocationChanged(Location location) { } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } }

Answer5:

Change this line

Location l = locationManager.getLastKnownLocation(provider); locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

to

Location l = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

then i think it will work.

Or you can follow <a href="http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/" rel="nofollow">this</a> tutorial to get the location using gps

Recommend

  • maps and core data swift 4
  • Why is this code not working? Hangman
  • UIScrollView setContentOffset: animated: not working
  • UrlEncode non-string properties for HTTP Post through HttpClient
  • How to load Q library with Require.js?
  • how can I compare dates in array to find the earliest one?
  • Responsive design method for collapsing a div
  • MySQL performance when updating row with FK
  • Private IP address in reserved subnet range
  • Ensure fsync did its job
  • Blackberry - Custom EditField Cursor
  • How do I get HTML corresponding to current DOM tree?
  • Body moving without any force applied? (Box2d)
  • QLineEdit password safety
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • script to move all files from one location to another location
  • Javascript Callbacks with Object constructor
  • Join two tables and save into third-sql
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • How to model a transition system with SPIN
  • ORA-29908: missing primary invocation for ancillary operator
  • Matrix multiplication with MKL
  • Proper folder structure for lots of source files
  • Error creating VM instance in Google Compute Engine
  • Acquiring multiple attributes from .xml file in c#
  • Free memory of cv::Mat loaded using FileStorage API
  • Hits per day in Google Big Query
  • Angular 2 constructor injection vs direct access
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • Android Google Maps API OnLocationChanged only called once
  • File not found error Google Drive API
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Is there any way to bind data to data.frame by some index?
  • Programmatically clearing map cache
  • reshape alternating columns in less time and using less memory
  • How can I use `wmic` in a Windows PE script?
  • Converting MP3 duration time
  • How can I use threading to 'tick' a timer to be accessed by other threads?