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

안드로이드 앱에서 위치 서비스 활성화 여부 확인하기 – 단계별 구현 가이드

개요

이 튜토리얼에서는 안드로이드 앱에서 위치 서비스가 켜져 있는지 확인하고, 꺼져 있을 경우 사용자에게 설정 화면으로 안내하는 방법을 단계별로 알아봅니다.

앱이 지도, 내비게이션 등 위치 기반 기능을 정상적으로 제공하려면 기기의 GPS 또는 네트워크 기반 위치 서비스가 반드시 활성화되어 있어야 합니다. 이 예제에서는 LocationManager를 사용해 두 가지 위치 공급자(GPS_PROVIDER, NETWORK_PROVIDER)의 상태를 점검하고, 둘 다 비활성화된 경우 다이얼로그를 통해 사용자에게 위치 설정을 요청합니다.

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:layout_margin="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enable Location" />

</RelativeLayout>

3단계: MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package app.tutorialspoint.com.sample;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationEnabled();
            }
        });
    }

    private void locationEnabled() {
        LocationManager lm = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
        boolean gps_enabled = false;
        boolean network_enabled = false;
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!gps_enabled && !network_enabled) {
            new AlertDialog.Builder(MainActivity.this)
                    .setMessage("GPS Enable")
                    .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .show();
        }
    }
}

코드 동작 원리

  • getSystemService(Context.LOCATION_SERVICE)를 통해 LocationManager 인스턴스를 가져옵니다.
  • isProviderEnabled() 메서드로 GPS 공급자와 네트워크 공급자 각각의 활성화 여부를 확인합니다.
  • 두 공급자가 모두 비활성화되어 있으면 AlertDialog를 표시해 사용자에게 알립니다.
  • 다이얼로그에서 Settings(설정) 버튼을 누르면 ACTION_LOCATION_SOURCE_SETTINGS 인텐트를 통해 시스템 위치 설정 화면으로 이동합니다.

참고: 최신 프로젝트에서는 지원 중단된 android.support.v7 라이브러리 대신 androidx.appcompat 패키지를 사용하는 것이 좋습니다.

4단계: 매니페스트에 위치 권한 추가

AndroidManifest.xml 파일에 아래와 같이 위치 관련 권한을 선언합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.sample">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_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>

ACCESS_FINE_LOCATION은 GPS를 이용한 고정밀 위치 권한, ACCESS_COARSE_LOCATION은 네트워크 기반의 저정밀 위치 권한입니다.

앱 실행 및 결과 확인

실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정하고 진행하겠습니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 도구 모음의 Run 아이콘을 클릭해 앱을 실행합니다. 실행 대상으로 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드 앱에서 위치 서비스 활성화 여부 확인하기 – 단계별 구현 가이드