我试图获取位置的值。 我调试了代码,我看到在我获得位置之后——android studio 没有将值返回给主要 Activity
我看到代码没有异常。
“getCurrentLocation”方法返回位置。 在我从 gps/网络(根据调试查看器的正确位置)获取位置后,我看到代码就在行
'if (!isGpsEnable && !isNetworkEnable) {'
并返回“位置”上的空值 即使“location”变量包含正确的 gps 位置。
代码:
public class TraceLocation implements LocationListener
{
public Location getCurrentLocation(Context context)
{
Location location = null;
try {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Boolean isGpsEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnable && !isNetworkEnable) {
// TODO !!! => no gps and no network !!!
} else if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (isNetworkEnable) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGpsEnable) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 10, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
catch(Exception e)
{
}
return location;
}
问题:
我使用的是 android 6.0(棉花糖)
为什么当方法返回时我得到的结果为空,即使我看到调试的返回值不为空
当我删除
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this);
和
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 10, this);
我也没有在调试中找到位置 - 为什么?????
最佳答案
从您提供的描述来看,在我看来您还没有完全实现原生 Android Location 机制所需的功能。
Android 中的位置提供程序以异步方式工作,因此您必须注册一个监听器,以便在生成位置更新时收到通知。
您不能期望系统立即响应(除非您使用 getLastKnownLocation(String provider)
方法 here)。
您的类包含一个implements LocationListener
,它应该强制您实现一系列方法,包括onLocationChanged(Location location)
。
这种方法是在获得位置时将被触发的方法;您可以检查 location
对象以查看其来源(无线或 GPS)和其他数据(速度、准确性等)。
查看官方指南了解更多详情here . 由于您的调试操作正在处理从环境(GPS 和无线网络)收集的数据,系统的行为将取决于这些变量。
关于android - 在我获得 gps/网络位置后,android 删除了该位置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543360/