ユーザーの場所を取得する必要があるアプリケーションを構築しています。私はアンドロイドの経験があまりないので、今、物事を動かす方法についての情報を読んでいます。
学習用のテスト アプリケーションを作成しました。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeField = (TextView) findViewById(R.id.latitude);
longitudeField = (TextView) findViewById(R.id.longitude);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
latitudeField.setText("Latitute not available");
longitudeField.setText("Longitude not available");
}
}
@Override
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latitudeField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
しかしgetLastKnownLocation()
、携帯電話をスリープ状態にすると、別の都市に行くと位置情報が更新されないため、使用するのは最善の方法ではないことを読みました. 代わりに何を使用することをお勧めしますか?