位置情報の取得
■位置情報の取得
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double lat = location.getLatitude(); double lng = location.getLongitude(); double alt = location.getAltitude(); String mes = "lat:" + lat + " lng:" + lng + " alt:" + alt; tv.setText(mes);
■位置が変わったときの取得
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
double alt = location.getAltitude();
String mes = "lat:" + lat + " lng:" + lng + " alt:" + alt;
tv.setText(mes);
}
@Override
public void onStatusChanged(String provider, int status,Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, // 10秒
10, // 10m
listener);
位置情報取得の解除
onPauseなどで
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE); lm.removeUpdates(pi);
■バックグラウンドでの位置取得
サービスから起動する。サービスから起動しないと解除が出来ない。
位置取得用のBroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String locationKey = LocationManager.KEY_LOCATION_CHANGED;
if(intent.hasExtra(locationKey)){
Location location = (Location)intent.getExtras().get(locationKey);
double lat = location.getLatitude();
double lng = location.getLongitude();
double alt = location.getAltitude();
String mes = "lat:" + lat + " lng:" + lng + " alt:" + alt;
Toast.makeText(context, mes,Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifst.xmlに登録
<receiver android:name=".MyReceiver" />
PendingIntentによる位置情報取得
ServiceのonStartCommandなどで。Serviceで PendingIntent pi; を宣言しておく。
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Intent i = new Intent(this, MyReceiver.class);
pi = PendingIntent.getBroadcast(this, 0, i,PendingIntent.FLAG_UPDATE_CURRENT);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, // 10-second interval.
10, // 10 meters.
pi);
位置情報取得の解除
ServiceのonDestroyなどで
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE); lm.removeUpdates(pi);
Android開発 虎の巻