我当前的位置始终返回null.我怎样才能解决这个问题?

dev*_*gal 17 null android location google-maps nullpointerexception

我想找到一个Android项目的当前位置.加载应用程序时,我的当前位置始终为null.我已经在清单等中设置了权限.当我找到当前位置时,我打算使用坐标来查找到地图上其他位置的距离.我的代码片段如下.为什么我总是得到一个空值?

locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);          
Criteria crit = new Criteria();     
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);    

if (location != null) {                 
    System.out.println("Location is not null!");
    lat = (int) (location.getLatitude() *1E6);
    longi = (int) (location.getLongitude() * 1E6);
    GeoPoint ourLocation = new GeoPoint(lati, longi);
    OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
                                                            "2nd String");
    CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
    custom.insertPinpoint(overlayItem);
    overlayList.add(custom);
    overlayList.clear();
} else {
   System.out.println("Location is null! " + towers);
   Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
                                                                    .show();
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*man 36

getLastKnownLocation()使用其他应用程序先前找到的位置.如果没有应用程序执行此操作,则getLastKnownLocation()返回null.

您可以对代码做一件事,以便更有可能获得最后已知位置 - 迭代所有已启用的提供程序,而不仅仅是最佳提供程序.例如,

private Location getLastKnownLocation() {
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        ALog.d("last known location, provider: %s, location: %s", provider,
                l);

        if (l == null) {
            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy()) {
            ALog.d("found best last known location: %s", l);
            bestLocation = l;
        }
    }
    if (bestLocation == null) {
        return null;
    }
    return bestLocation;
}
Run Code Online (Sandbox Code Playgroud)

如果您的应用无法在没有位置的情况下进行交易,并且如果没有最后的已知位置,则需要监听位置更新.你可以看看这个类的例子,

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

请参阅方法onStartCommand(),检查网络提供程序是否已启用.如果没有,它使用最后已知的位置.如果已启用,则会注册以接收位置更新.

  • 为什么`if(bestLocation == null){return null; 返回bestLocation;`而不仅仅是`返回bestLocation;`?另见[here](http://stackoverflow.com/questions/2250597/find-current-location-latitude-and-longitude#comment25840492_2251680) (7认同)

Aka*_*ngh 8

如果您找到设备的当前位置,请在主类中使用以下方法

public void find_Location(Context con) {
    Log.d("Find Location", "in find_location");
    this.con = con;
    String location_context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) con.getSystemService(location_context);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        locationManager.requestLocationUpdates(provider, 1000, 0,
            new LocationListener() {

                public void onLocationChanged(Location location) {}

                public void onProviderDisabled(String provider) {}

                public void onProviderEnabled(String provider) {}

                public void onStatusChanged(String provider, int status,
                        Bundle extras) {}
            });
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            addr = ConvertPointToLocation(latitude, longitude);
            String temp_c = SendToUrl(addr);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在清单文件中添加用户权限方法

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Run Code Online (Sandbox Code Playgroud)