最終更新:
moonlight_aska 2013年09月08日(日) 14:09:37履歴
位置情報を取得するには, ロケーションマネージャ(LocationManager)クラスを利用する.


- Gps03.java
- getSystemServiceメソッドで, LOCATION_SERVICEを指定してLocationManagerのインスタンスを取得する.
- onResumeメソッド
- LocationManager#requestLocationUpdatesメソッドで, "GPS_PROVIDER"を指定して, 位置情報の更新をリクエストする.
- onPauseメソッド
- LocationManager#removeUpdatesメソッドで, 位置情報の更新を止める.
- onLocationChangedメソッド
- Location#getXXXメソッドで, 位置情報を取得する.
package com.moonlight_aska.android.gps03;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class Gps03 extends Activity implements LocationListener {
private LocationManager manager = null;
private TextView latitude;
private TextView longitude;
private TextView altitude;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// GPSサービス取得
manager = (LocationManager)getSystemService(LOCATION_SERVICE);
latitude = (TextView)findViewById(R.id.latitude_id);
longitude = (TextView)findViewById(R.id.longitude_id);
altitude = (TextView)findViewById(R.id.altitude_id);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
if(manager != null) {
manager.removeUpdates(this);
}
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
if(manager != null) {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
super.onResume();
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String str = "緯度:" + location.getLatitude();
latitude.setText(str);
str = "経度:" + location.getLongitude();
longitude.setText(str);
str = "高度:" + location.getAltitude();
altitude.setText(str);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
- AndroidManifest.xml
- 位置情報を取得するには, "android.permission.ACCESS_FINE_LOCATION"パーミッションを設定する.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moonlight_aska.android.gps03"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".Gps03" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
コメントをかく