我需要獲取當前用戶在Android應用程序上的位置,所以我已經閱讀了一些教程和Web上的示例,但我看到在所有示例中,位置都是從一個「onLocationChange」意味着每當位置改變時,「onLocationChange」中的代碼就被執行。Android - 獲取位置只有一次
我只需要在應用程序啓動時獲取用戶位置。
感謝您的幫助!
我需要獲取當前用戶在Android應用程序上的位置,所以我已經閱讀了一些教程和Web上的示例,但我看到在所有示例中,位置都是從一個「onLocationChange」意味着每當位置改變時,「onLocationChange」中的代碼就被執行。Android - 獲取位置只有一次
我只需要在應用程序啓動時獲取用戶位置。
感謝您的幫助!
您可以使用LocationManager執行此操作。 getLastKnownLocation
在主活動將這個:
boolean bFirst = true;
function void onCreate(blabla) {
if(bFirst) {
//Do your stuff to get the location
bFirst = false;
}
}
把相同的的onResume();
這使得代碼只執行一次,但條件測試不斷被探測 – 2011-01-19 14:04:44
您可以使用下面的代碼獲取上一個已知位置。它獲取位置提供者並向後遍歷數組。即從GPS開始,如果沒有GPS則獲取網絡位置。您可以在需要獲取位置時調用此方法。
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
對於其火衛一的建議才能正常工作,你必須讓你的AndroidManifest.xml
這將讓你擺脫錯誤的接收0.0
添加這些行內訪問getGPS()
方法:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.LOCATION_HARDWARE" />
感謝您的回答,從您的鏈接看起來,我總是需要設置一個提供商......是嗎?讓我得到更好的提供者並將其設置在getLastKnownLocation中? – 2011-01-19 14:07:27
是的,那是你需要做的。 – elevine 2011-01-19 14:23:04