为什么我的位置为空? - Android

时间:2013-06-17 15:53:09

标签: android android-location android-maps-v2

为什么我的位置变量的值为null?我正确设置了我的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

我的代码出了什么问题?

2 个答案:

答案 0 :(得分: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" />

答案 1 :(得分:0)

// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

检查gps是否已启用。