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

動作時の注意点:
(1) GPSをONにする. OFFの場合, locationがnullとなる.
(2) 最後に取得した位置情報がない場合, locationがnullとなる.

- Gps04.java
- getSystemServiceメソッドで, LOCATION_SERVICEを指定してLocationManagerのインスタンスを取得する.
- LocationManager#getLastKnownLocationメソッドで, "GPS_PROVIDER"を指定して, 最後に取得した位置情報を取得する.
package com.moonlight_aska.android.gps04;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.app.Activity;
public class Gps04 extends Activity {
private LocationManager manager = null;
private TextView latitude;
private TextView longitude;
private TextView altitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latitude = (TextView)findViewById(R.id.latitude_id);
longitude = (TextView)findViewById(R.id.longitude_id);
altitude = (TextView)findViewById(R.id.altitude_id);
// GPSサービス取得
manager = (LocationManager)getSystemService(LOCATION_SERVICE);
// 最後の位置情報取得
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String str = "緯度:" + location.getLatitude();
latitude.setText(str);
str = "経度:" + location.getLongitude();
longitude.setText(str);
str = "高度:" + location.getAltitude();
altitude.setText(str);
}
else {
Log.e("GPS", "Can't get last location.");
}
}
}
動作時の注意点:
(1) GPSをONにする. OFFの場合, locationがnullとなる.
(2) 最後に取得した位置情報がない場合, locationがnullとなる.
- 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.gps04"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.moonlight_aska.android.gps04.Gps04"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
コメントをかく