首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >`locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);`总是返回true

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

Stack Overflow用户
提问于 2015-08-29 12:44:16
回答 1查看 1.3K关注 0票数 0

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

代码语言:javascript
复制
    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);

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

我也读过this的问题。显然有完全相反的问题,并尝试了这个解决方案。这也没用。我正在三星G5上进行测试。为什么会发生这种事。是代码有问题还是我的问题有其他解决方案。

以下是代码:

代码语言:javascript
复制
@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问题似乎有相同的问题。这是硬件故障吗?如果是的话,还有其他的可能性吗?我也会测试另一个设备说明-4,并让你知道。

EN

回答 1

Stack Overflow用户

发布于 2015-08-29 12:49:55

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

在任何时候,您都可以得到一个null位置,所以不必担心是否启用了GPS,而应该担心您返回的位置是否为空。

如果没有最后一个位置,getLastKnownLocation()可以返回null

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32286193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档