0

为什么我的位置变量的值为空?我正在正确设置我的 LocationManager。

这是我的源代码:

    //Get the current location
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    myCriteria = new Criteria();
    String provider = locationManager.getBestProvider(myCriteria, true);
    Location location = locationManager.getLastKnownLocation(provider);
    boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
    //Location location;

    if (isGpsEnabled) { 
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }
    else { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    Log.i(TAG, "Provider is: "+provider);
    Log.i(TAG, "Location is: "+location);

这是 logcat 输出:

06-17 10:40:52.637: D/dalvikvm(15106): GC_FOR_ALLOC freed 534K, 7% free 10586K/11360K, paused 16ms, total 16ms
06-17 10:40:52.677: I/OGT.RideTracking(15106): Provider is: gps
06-17 10:40:52.677: I/OGT.RideTracking(15106): Location is: null
06-17 10:40:52.677: D/AndroidRuntime(15106): Shutting down VM

我的代码有什么问题?

4

2 回答 2

1

试试这个代码

这些变量是类变量

LocationManager locManager;
LocationListener locListener;

create在方法上添加此代码

locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);

在同一文件中添加此代码

public class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location loc) {
        Log.d("tag", "Finding Latitude");
        double lat = loc.getLatitude();
        Log.d("tag", "Lat: " + String.valueOf(lat));
        Log.d("tag", "Finding Longitude");
        double lon = loc.getLongitude();
        Log.d("tag", "Lon: " + String.valueOf(lon));
        Log.i(Tag, loc.toString());
        String Text = "Lat: " + lat + "\nLon: " + lon;

        // Display location
        locManager.removeUpdates(locListener);
    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {

    }

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

    }
}

AndroidManifest.xml需要

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-06-17T16:09:08.683 回答
0
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

检查是否启用了gps。

于 2013-06-17T15:57:54.940 回答