Androidプログラマへの道 〜 Moonlight 明日香 〜 - GPSの状態を取得する
GPS(Global Positioning System)による位置測位機能のON/OFF状態を取得するには, Settings.Secureクラスを利用する.

GPSのON/OFF状態取得

  • Gps01.java
    • Settings.Secure#getStringメソッドにContentResolverとLOCATION_PROVIDERS_ALLOWEDを指定して, 許可済みの位置測位プロバイダー一覧を文字列で取得する.
    • "gps"が含まれているか調べる.
     注) Wi-Fi/モバイルネットワークによる位置測位機能がON状態の場合, "network"が含まれる.
    • 含まれていない場合は, "位置情報とセキュリティの設定"画面を表示する.
package com.moonlight_aska.android.gps01;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class Gps01 extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // 位置測位プロバイダー一覧を取得
    String providers = Settings.Secure.getString(
           getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    Log.v("GPS", "Location Providers = " + providers);
    if(providers.indexOf("gps", 0) < 0) {
      // 設定画面の呼出し
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      startActivity(intent);
    } else {
      Toast.makeText(getApplicationContext(), "GPS : ON", Toast.LENGTH_LONG).show();
    }
  }
}
  • 動作例
端末:SHARP SH-03C / Android 2.2
    • GPSがOFFの場合
    • GPSがONの場合