0

每隔一段时间,我的应用程序在尝试获取用户位置时就会崩溃。不幸的是我没有这个错误,因为当我插入我的电脑时它从未发生过......

我正在使用它来获取我的用户位置:

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

我在想有时这可能是空的?如果是这样,我该如何解决这个力关闭?

4

4 回答 4

2

它在获取位置时不会强制关闭..它在分配经度和纬度时强制关闭..在分配if(location!=null)值之前放置一个

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

//location might be null so
if(location != null)
{
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
}
于 2013-11-08T14:53:12.977 回答
0

您不能保证位置不会为空(可能没有最后一个已知位置),因此您将有一个 NullPointerException

location.getLongitude()

在继续之前检查该位置!= null。

于 2013-11-08T14:52:57.143 回答
0

当有可能发生异常时,请始终使用 Try & catch 块。如果 location 返回 null,您将得到 NullPointerException。

try {

        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
    } catch (Exception e) {

    }
于 2013-11-08T15:07:47.793 回答
0

我建议不要使用自己的 GPS .. 使用 Fused Location Provider:

这是一个例子: http ://www.kpbird.com/2013/06/fused-location-provider-example.html?m=1

于 2013-11-08T15:25:54.823 回答