[英]Waiting for GPS location before proceeding Android
我知道周圍有許多類似的問題,但在我的搜索中找不到合適的答案。
我的App的活動依賴於GPS位置來起作用。 如果應用程序在啟動后立即運行,則由於空指針異常等(位置為空)而崩潰。 我知道這些是我的編程錯誤,我應該處理這些異常,但是在找到GPS修復之前,該活動仍然沒有用。
當應用崩潰時,我會看到“正在搜索GPS”圖標,如果放置足夠長時間,則會找到GPS位置,並且該應用可以正常運行。
我創建了另一個活動以充當主屏幕,當找到GPS位置時,該按鈕將使該按鈕鏈接到上述活動。 問題在於它似乎找不到或正在尋找GPS信號。 我的意思是,不會顯示“正在搜索GPS”圖標,並且永遠不會啟用該按鈕。 該家庭活動的代碼如下,我錯過了什么嗎?
我的活動實現了LocationListener,下面的代碼在Activity的“ onCreate”方法中。 “ startExplore”啟動我的GPS依賴活動。
exploreButton = (Button) findViewById(R.id.button1);
exploreButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startExplore();
}
});
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
exploreButton.setEnabled(false);
exploreButton.setText("Finding location . . .");
}
這是我的“ onLocationChanged”方法。 正如我上面所說,與我的其他活動不同,我沒有得到“正在搜索GPS”圖標,盡管該位置與我的其他活動中使用的方法相同,但似乎未找到該位置。 那么,這是等待找到位置的正確方法,並且有人可以發現任何錯誤嗎?
public void onLocationChanged(Location location) {
exploreButton.setEnabled(true);
exploreButton.setText("Found signal");
}
調用locationManager.requestLocationUpdates(locationProvider, 0, 0, this)
以獲取更新的位置。。這可能是問題的根源。由於這個原因,我認為沒有啟動“僅搜索GPS”。
將其移出onCreate方法或將其放入處理程序中。
例:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//methods you want.
}
}, 100);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.