【发布时间】:2021-05-13 13:22:52
【问题描述】:
我试图每隔一段时间获取用户的位置,并且我需要始终在变量中包含一些内容,以便我可以检查用户是否靠近他/她试图解锁的门。
这是我要运行的代码。我正在扩展 AppCompatActivity 并实现 LocationListener。
protected LocationManager locationManager;
protected double currentLatitude, currentLongitude;
protected double storeLatitude, storeLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Utils.showMessage(StoreActivity.this, "You must allow GPS services, so that we can make sure that you're near the store you're trying to unlock.");
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
}
@Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
有时我确实知道位置。所以代码有效。但是有时我可以等待很长时间而根本没有任何更新,所以这里一定有问题。我确定手机上也允许 GPS 服务。
有什么想法可以改进吗?我需要始终在变量中有某种位置,而不是为空。
提前致谢!
【问题讨论】: