[英]How to deal with getLastKnownLocation returning null?
我正在開發的Android應用程序中使用位置服務。 經過研究,我發現getLastKnownLocation()
是獲取用戶最近位置的最快方法。 我沒有問題,因為我的應用程序模塊不需要用戶的當前位置,因此它有點過時了。 這個解決方案對我來說很好,因為在那個給定的時刻我真的不需要用戶的確切位置。
但是, getLastKnownLocation
的明顯問題是,如果該設備沒有存儲最新位置,或者您最近重新啟動了該設備,則它必然會返回null
。
我的問題是,當getLastKnownLocation
為null
時getLastKnownLocation
怎么辦?
這是我提出的:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestProvider = lm.getBestProvider(criteria, false);
Location l = lm.getLastKnownLocation(bestProvider);
if(l != null) {
Log.d("Lat", String.valueOf(l.getLatitude()));
Log.d("Lng", String.valueOf(l.getLongitude()));
}
else {
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(),
PendingIntent.FLAG_UPDATE_CURRENT);
lm.requestSingleUpdate(bestProvider, pi);
Location ln = lm.getLastKnownLocation(lm.getBestProvider(criteria, false));
// Still returns null
Log.d("NewLat", String.valueOf(ln.getLatitude()));
Log.d("NewLng", String.valueOf(ln.getLongitude()));
}
因此,對reqyestSingleUpdate
的調用不應該存儲最新的位置數據嗎? 但是,它似乎不起作用。 我要去哪里錯了? 您如何解決這個問題?
因此,將他的課程插入到您的應用中,然后在您的活動中像這樣使用它
mMyLocHelper = new MyLocationHelper();
// An object with callback that will be called after location was found
LocationResult locationResult = new LocationResult() {
@Override
public void gotLocation(Location location) {
if (location != null) {
mUserLocation = location;
// Here my action after location is known (on UI thread!)
runOnUiThread(new Runnable() {
@Override
public void run() {
myAction();
}
});
}
else {
// No location was found
runOnUiThread(new Runnable() {
@Override
public void run() {
informUser();
}
});
}
}
};
// We state, that we can wait for 20 seconds for the location, and start the process
if (mMyLocHelper.getLocation(this, locationResult, 20)) {
mLocationEnabled = true;
}
else {
mLocationEnabled = false;
// Localization is turned off. Inform user
informUser();
}
無法保證您將獲得位置。
1)您無法避免程序中出現“位置未知”狀態。 在某個時刻,位置確實是未知的。
2)您可以使用getBestProvider() ,但是可以在一段時間內使用其他提供程序。 不能保證第二提供商會正常工作(電話中可能沒有SIM卡)。
3)您可以在首選項中存儲最后一個已知的位置,請參見Context.getSharedPreferences() 。
4)您可以“在北極”開始(以北極的坐標:-)。
但是,您的應用程序可能永遠不會接收位置數據:它可能是在金屬太多而無法GPS工作的建築物中啟動的,並且手機插槽中沒有SIM卡(如果是手機而不是平板電腦) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.