![](/img/trans.png)
[英]isProviderEnabled(LocationManager.NETWORK_PROVIDER) returns true even when no internt is enabled
[英].isProviderEnabled(LocationManager.NETWORK_PROVIDER) returns always false when gps is off?
如果 GPS 关闭,是否可以从 NETWORK 获取位置?
我的演示可以从网络和 GPS 获取当前用户位置,但前提是 GPS 开启。
如果我尝试从 LastKnownLocation 获取位置,我也会得到 null。
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
startActivity(new Intent(MainActivity.this, Permissions.class));
return;
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPS && !isNetwork) {
Log.d("TAG", "gps and network false");
}else {
if (isGPS) {
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
Log.i("TAG", "gps loc found");}
}
if (isNetwork) {
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (loc != null) {
Log.i("TAG", "network loc found");
}
}
我在下面测试了这段代码。 如果我关闭设备gps,它也会返回位置null: GPSTracker.java
如果您尝试从网络请求位置作为 GPS 的后备,则需要启用ACCESS_COARSE_LOCATION
。 此外,即使启用了权限,您也必须请求位置更新,以刷新和更新最后的网络位置。 只有在那之后,您才会拥有最后一个已知位置 available ,否则,您确实会得到 null 。
为了使您的代码工作,您可能只需要在使用getSystemService(Context.LOCATION_SERVICE);
之前调用GPSTracker.getLocation()
getSystemService(Context.LOCATION_SERVICE);
您可以在此处查看getLastKnownLocation
的文档: https : //developer.android.com/reference/android/location/LocationManager#getLastKnownLocation ( getLastKnownLocation
)
从给定的提供程序获取最后一个已知位置,如果没有最后一个已知位置,则为 null。 在某些情况下,返回的位置可能很旧,因此应始终检查位置的年龄。
👉这永远不会激活传感器来计算新位置,并且只会返回缓存的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.