Android
 Computer >> コンピューター >  >> プログラミング >> Android

Android端末のGPSが有効になっているか確認する方法【サンプルコード付き】

はじめに

この記事では、Android端末のGPS(位置情報)が現在有効になっているかどうかを、アプリからプログラム的に判定する方法を解説します。さらに、GPSが無効だった場合にユーザーへ通知し、位置情報の設定画面へ誘導するダイアログを表示するところまでを実装します。

実装手順

ステップ1:Android Studioで新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成してください。

ステップ2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。ここでは、画面中央に「Detecting GPS in Android Device」というテキストを表示するシンプルなレイアウトを定義しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="24sp"
      android:textStyle="bold"
      android:layout_centerInParent="true"
      android:text="Detecting GPS in Android Device" />
</RelativeLayout>

ステップ3:MainActivity.java を実装する

src/MainActivity.java に以下のコードを追加します。LocationManagerisProviderEnabled() メソッドを使って GPS_PROVIDER の状態を確認し、GPSが無効な場合はダイアログを表示して、位置情報設定画面へ遷移できるようにしています。

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
      if (Objects.requireNonNull(locationManager).isProviderEnabled(LocationManager.GPS_PROVIDER)) {
         Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
      } else {
         showGPSDisabledAlertToUser();
      }
   }
   private void showGPSDisabledAlertToUser() {
      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
      alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
         .setCancelable(false).setPositiveButton("Goto Settings Page To Enable GPS",
         new DialogInterface.OnClickListener() {
         
         public void onClick(DialogInterface dialog, int id) {
            Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(callGPSSettingIntent);
         }
         });
      alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
         }
      });
      AlertDialog alert = alertDialogBuilder.create();
      alert.show();
   }
}

ステップ4:AndroidManifest.xml に権限を追加する

位置情報機能を利用するため、androidManifest.xml に ACCESS_FINE_LOCATION パーミッションを宣言します。以下のコードを参考にしてください。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
         <activity android:name=".MainActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
   </application>
</manifest>

コードのポイント

  • LocationManager:システムの位置情報サービスへアクセスするためのクラスです。getSystemService(LOCATION_SERVICE) でインスタンスを取得します。
  • isProviderEnabled():指定したプロバイダー(ここでは GPS_PROVIDER)が有効かどうかを boolean 値で返します。
  • AlertDialog:GPSが無効な場合にユーザーへ通知し、「設定画面へ移動」ボタン押下時に Settings.ACTION_LOCATION_SOURCE_SETTINGS を呼び出して位置情報設定画面を開きます。
  • パーミッション:正確な位置情報を扱うため、android.permission.ACCESS_FINE_LOCATION の宣言が必須です。

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。実際のAndroid端末をPCに接続していることを前提とします。Android Studioから実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。デバイス選択画面で接続中のモバイル端末を選択すると、端末側に以下のような画面が表示されます。

Android端末のGPSが有効になっているか確認する方法【サンプルコード付き】

Android端末のGPSが有効になっているか確認する方法【サンプルコード付き】

  1. Androidスマホの端末名を変更する方法|Bluetooth・Playストアの名前も解説

    同じようなAndroidスマートフォンが数多く存在する中で、自分のデバイスを見分けやすくしたいと思ったことはありませんか?Androidでは端末の名前を自由に変更でき、好きな名前を付けることが可能です。 この設定には、システムのコア設定を書き換えたり、カスタムROMをインストールしたりする必要は一切ありません。名前を変更する機能は、最初から端末に組み込まれています。この記事では、スマートフォン本体の名前、Bluetooth名、さらにGoogle Playストア上のデバイス名を変更する方法を詳しくご紹介します。 Android端末の名前を変更する 名前の変更手順は機種によって多少異なりますが、ほ

  2. AndroidスマホをGPSトラッカーとして活用する方法

    GPSは、紛失や盗難に遭ったデバイスの回収や、Googleマップを使ったドライブ中のナビゲーションに非常に便利な機能です。さらに嬉しいことに、GPSはインターネットに接続していなくても動作します。事前に地図をダウンロードしておけば安心です。 では、AndroidスマホをGPSトラッカーとして使うにはどうすればよいのでしょうか?最も信頼性の高い選択肢ではないかもしれませんし、無視できない欠点もありますが、いざというときには十分役立ちます。ここでは、AndroidスマホをGPSトラッカーとして活用する方法を詳しく解説します。 注意: 本記事の手順はAndroid 8.0 Oreo搭載のSamsun