Androidプログラマへの道 〜 Moonlight 明日香 〜 - 最後の位置情報を取得する
最後に取得した位置情報を取得するには, ロケーションマネージャ(LocationManager)クラスを利用する.



最後の位置情報の取得

  • Gps04.java
    • getSystemServiceメソッドで, LOCATION_SERVICEを指定してLocationManagerのインスタンスを取得する.
    • LocationManager#getLastKnownLocationメソッドで, "GPS_PROVIDER"を指定して, 最後に取得した位置情報を取得する.
     注) ネットワークからの位置情報取得の場合は, "NETWORK_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"パーミッションを設定する.
     注) ネットワークによる位置情報取得の場合は, "android.permission.ACCESS_COARSE_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>