クラス直下で宣言
private PendingIntent pi; LocationManager mLocationManager; ReceiveLocation receiver;
onCreate内に以下を記述
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
receiver = new ReceiveLocation();
//指定したIntentに反応するようにReceiverにIntentFilterを登録
final IntentFilter filter = new IntentFilter();
filter.addAction("com.android.practice.ACTION_LOCATION_UPDATE");
registerReceiver(receiver, filter);
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// GPSプロバイダ状態取得
if(!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
//無効状態
} else {
//有効状態
}
// ネットワーク(3GまたはWi-Fi)プロバイダ状態取得
if(!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
//無効状態
} else {
//有効状態
}
GpsStatus.Listenerをimplementsで実装します。
onGpsStatusChangedメソッドを上書きします。
@Override
public void onGpsStatusChanged(int event) {
if (event == GpsStatus.GPS_EVENT_FIRST_FIX) {
} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
} else if (event == GpsStatus.GPS_EVENT_STARTED) {
} else if (event == GpsStatus.GPS_EVENT_STOPPED) {
}
}
端末自身の[設定]-[位置情報とセキュリティ]より、GPS機能がONに設定されているかを取得します。
OFFに設定されている場合にダイアログを表示して設定画面を呼び出す処理をしています。
// GPS機能設定の状態を取得
String GpsStatus = android.provider.Settings.Secure.getString(getContentResolver(), Secure.LOCATION_PROVIDERS_ALLOWED);
if (GpsStatus.indexOf("gps", 0) < 0) {
//GPSが無効だった場合
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("GPS機能がOFFになっています。\n設定画面を開きますか?");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//設定画面を呼び出す
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
ad.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
//何もしない
}
});
ad.create();
ad.show();
} else {
//GPSが有効だった場合
}
API Level3(Android 1.5)以降、セキュリティ上の問題で設定を強制的に変更することはできません。