`locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);`总是返回true

时间:2015-08-29 12:44:16

标签: java android nullpointerexception location locationmanager

我正在测试使用Location服务的应用。每当我的位置服务关闭时,它都会返回null,导致NPE (Null Pointer Exception)。经过一番搜索,我发现了

    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);

应该返回正确的boolean value,但在测试我的应用时,似乎总是返回true导致NPE (Null Pointer Exception)并导致我的应用崩溃。

我还阅读了this个问题。这显然与完全相反的问题并尝试了解决方案。这也行不通。我正在测试三星G5。为什么会这样呢?代码中有什么问题,或者我的问题是否有另一种解决方案。

以下是代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    isGPSEnabled = false;
    intentThatCalled = getIntent();
    String m2txt = intentThatCalled.getStringExtra("v2txt");
    getLocation(m2txt);
}
public void getLocation(String n2txt) {
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    criteria = new Criteria();
    bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
    location = locationManager.getLastKnownLocation(bestProvider);
    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
    if (isGPSEnabled==true) {
        Log.e("TAG", "GPS is on");
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
        searchNearestPlace(n2txt);
    }
}

我还是android的初学者。 请帮忙。

修改 This问题似乎在同一个硬件模型上存在同样的问题。这是硬件错误吗?如果是,是否还有其他可能性。我还将在另一台设备Note-4上进行测试并告知您。

1 个答案:

答案 0 :(得分:1)

问题的解决方案是从不假设您有位置,只是因为您的GPS启用并不意味着您将获得一个位置。

您可以随时获取null位置,而不必担心GPS是否启用,您应该担心返回的位置是否为空。

如果没有最后位置,

getLastKnownLocation()可以返回null