Android - Trouble in getting location coordinates

2019-04-12 08:45发布

问题:

I am new to android. So please apologize if my question is simple and help me.

I am developing an android app in which I try to get users location only using GPS service (As I am developing an app which needs to run in android devices even with no internet).

My code is given below:

My activity:

public class MyView extends Activity implements OnClickListener, Runnable
    {
       LocationManager itsLocationManager;
       LocationListener itsLocationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
      itsLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      itsLocationListener = new MyLocationListener(this, itsLocationManager);

      getLocationAndSendMessage();
    }

    private void getLocationAndSendMessage() 
    {
      try 
      {
        itsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, itsLocationListener);
      } 
      catch (Exception theException) 
      {
        theException.printStackTrace();
        ToastMsgUtil.showErrorMessage("Problem in retrieving your current location! Please try again.", this);  
       }
     }

MyLocationListener.java:

public class MyLocationListener implements LocationListener
{
    Context itsContext;
    LocationManager itsLocationManager;

    public MyLocationListener(Context theContext, LocationManager theLocationManager) 
    {
        itsContext = theContext;
        itsLocationManager = theLocationManager;
    }

        @Override
    public void onLocationChanged(final Location theLocation) 
    {
                //My Location processing code
                itsLocationManager.removeUpdates(SafemateLocationListener.this);
         }
}

AndroidManifest.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" />

As I said above, I need to get location only through GPS (as no internet in users mobile).

  • On debugging, I found that I am not receiving any location updates in onLocationChanged method when I am using LocationManager.GPS_PROVIDER.
  • However, when I tried with LocationManager.NETWORK_PROVIDER, I receive location updates.

Can anyone please say what I did wrong in the above code? Have I missed any thing?

Help please. Thank You.

回答1:

Getting correct coordinates using GPS in a stable, working and compatible way is a mess. I remember a posting somewhere here at stackoverflow.com but can't find it at the moment. So I'd suggest to take the GPS-related code out of WLocate.java which works using all known Android versions. Or use the libwlocate, it encapsulates the functionality you're looking for.