我無法理解整個獲取的用戶位置。我遵循了LocationManager的教程。它從GPS提供商獲取最後一個已知位置。從我可以告訴的是一些用戶沒有最後一個知道的位置,它返回NULL。無法獲取所有用戶位置android
我認爲如果NULL將使用GPS並嘗試獲取用戶位置,則下面的代碼將會出現。但事實並非如此。我如何強制android來檢索用戶位置?而不是隻顯示我的NULL消息,不工作?
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//construct url
String url = "myURl";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
else{
//pop toast saying cant get location
Toast.makeText(getApplicationContext(), "Can not get your location at this time", Toast.LENGTH_LONG).show();
}
更新:
看一些的答覆後,我爲什麼不能做這樣的事情只得到用戶的位置,在每個他打開此活動時間:
final LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
LocationListener listener = new LocationListener();
manager.requestSingleUpdate(criteria, listener, null);
和我重寫與
@Override
public void onLocationChanged(Location lastKnownLocation) {
if (lastKnownLocation != null) {
// whatever needs to be done
}
}
位置監聽器,但我得到的錯誤:位置Listener是抽象的,不能實例化就行了newLocationListener();
我有點得到,我需要requestSingleUpdate應該得到用戶的新位置。但是我很困惑你的代碼如何適合我的? – Mike
我在上面的帖子中加入了更多的內容。 – Mike
你的代碼從'if(location!= null)'塊開始,應該在我寫'//需要做的任何事情'的地方開始。請注意,如果您請求'Criteria.ACCURACY_FINE',GPS可能需要一段時間才能解決問題,並且會調用偵聽器回調。 –