2

我最初有错误的代码,Festus 帮助注意到我有一个空位置:

            LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();   

我使用了 Festus GPSTracker 类,并按照他的指示在我的活动中添加了它。下面是我的活动课:

package com.bob.terranet;

import java.util.List;

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.net.Uri;
    import android.os.Bundle;

    public class Contactus extends Activity {

        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.contactus);

             double latitude = -1, longitude=-1;
              GPSTracker gps = new GPSTracker(Contactus.this);
              if (gps.canGetLocation()) {

                  latitude = gps.getLatitude();
                  longitude = gps.getLongitude();
        }





            String geoUriString = "http://maps.google.com/maps?" + 
                       "saddr=" + latitude + "," +  longitude + "&daddr=" + 33.947917 + "," + 35.645142;





            Intent mapCall = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUriString));

                    startActivity(mapCall);
        }



    }

问题是它总是给我 -1, -1 作为位置,表明网络提供商是错误的,而我有网络连接。

4

3 回答 3

2

您的位置为空

Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

此调用返回 null 并且您尝试从 null ==> 获取值

Caused by: java.lang.NullPointerException     03-15 11:25:50.855: E/AndroidRuntime(9992):     at com.bob.terranet.Contactus.onCreate(Contactus.java:22)

在继续之前尝试检查您的位置是否不为空

有时 GPS_provider 无法正常工作,因此始终建议使用 bestProvider

Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

如果您的问题仍然存在,请使用此类检索您的 lon 和 lat

public class GPSTracker 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; // 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;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    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.d("GPS Enabled", "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;
    }


    public void onLocationChanged(Location location) {
    }


    public void onProviderDisabled(String provider) {
    }


    public void onProviderEnabled(String provider) {
    }


    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


}

把它放在你的活动中

 GPSTracker gps = new GPSTracker(Contactus.this);
      if (gps.canGetLocation()) {

         double latitude = gps.getLatitude();
         double longitude = gps.getLongitude();
}
于 2013-03-15T09:35:40.907 回答
1

您是否在 Manifast 文件中添加了权限?

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

lastKnownLocation是空的,你会收到一个空指针异常。

试试这个代码来获得你的第一个位置:

List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();

if ((time > minTime && accuracy < bestAccuracy)) {
  bestResult = location;
  bestAccuracy = accuracy;
  bestTime = time;
}
else if (time < minTime && 
         bestAccuracy == Float.MAX_VALUE && time > bestTime){
  bestResult = location;
  bestTime = time;
}
}
}

取自这里:

http://android-developers.blogspot.co.il/2011/06/deep-dive-into-location.html

我建议你也阅读这篇博文......

基本上,此代码将遍历所有可用的提供程序以获得最佳可用位置。

于 2013-03-15T09:28:52.173 回答
1

这个问题已经被问了几十次了。重要的是要注意 GPS 和 LocationManager 是事件驱动的,并且按照回调原则运行。换句话说,当 GPS 修复并触发 OnLocationChanged 而不是 before 时,您将获得位置。你得等一等。说我现在想要这个位置是不好的,因为你不能拥有它。直到 OnLocationChanged 第一次触发 getLasKnownLocation 将为 null 并且正如其他人所指出的那样,这是您的错误的原因。

于 2013-03-15T11:14:37.013 回答