Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 기기에서 GPS 활성화 여부를 확인하는 방법

이 예제는 안드로이드 기기에서 GPS(위치 서비스)가 켜져 있는지 꺼져 있는지 프로그래밍 방식으로 확인하는 방법을 보여줍니다. LocationManager를 활용하면 간단하게 구현할 수 있으며, GPS가 비활성화된 경우 사용자에게 알림 대화상자를 띄워 설정 화면으로 안내할 수도 있습니다.

1단계: 새 프로젝트 생성

Android Studio에서 새 프로젝트를 생성합니다. 메뉴에서 File → New Project를 선택하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력한 뒤 진행하세요.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?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 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 핵심 로직은 LocationManager.isProviderEnabled() 메서드를 통해 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();
    }
}

코드 설명

onCreate() 메서드에서 시스템 서비스인 LOCATION_SERVICE를 통해 LocationManager 인스턴스를 가져온 뒤, isProviderEnabled(LocationManager.GPS_PROVIDER)로 GPS가 활성화되어 있는지 확인합니다. GPS가 켜져 있으면 토스트 메시지를 표시하고, 꺼져 있으면 사용자에게 위치 설정 화면으로 이동할지 묻는 대화상자를 띄우는 showGPSDisabledAlertToUser() 메서드를 호출합니다. 사용자가 확인 버튼을 누르면 ACTION_LOCATION_SOURCE_SETTINGS 인텐트를 통해 위치 설정 화면으로 이동합니다.

4단계: 매니페스트 파일 수정

androidManifest.xml 파일에 아래와 같이 위치 권한을 추가합니다. 이 권한이 없으면 정상적으로 동작하지 않으므로 반드시 선언해야 합니다.

<?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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 결과가 표시됩니다.

GPS가 켜져 있는 경우에는 "GPS is Enabled in your device"라는 토스트 메시지가 나타나고, 꺼져 있는 경우에는 GPS 활성화를 유도하는 대화상자가 화면에 표시됩니다.

안드로이드 기기에서 GPS 활성화 여부를 확인하는 방법

안드로이드 기기에서 GPS 활성화 여부를 확인하는 방법