Google マップで現在地をリクエストするときと同じように、現在地を取得するのを待たなければなりません。場所を取得できない場合は、エラーを通知して何もしません。
こことウェブで回答を読みましたが、メソッドを使用する必要があるとすべて言われていますがgetLastKnownLocation
、これは必要ありません。現在の場所が必要なだけです。そうでなければ、私は何もしません。
昨日からこれを読んでください:GPS Android - 測位を一度だけ取得
ただし、現在の場所を取得する方法は次のとおりです。
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// if it is less than two minutes old,
// otherwise wait for the update below
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
// You need to call this whenever you are done:
// mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}