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

안드로이드에서 프로그래밍 방식으로 GPS 켜기/끄기 구현하는 방법

이 튜토리얼에서는 안드로이드 앱에서 GPS(위치 서비스)의 현재 상태를 확인하고, 버튼 하나로 위치 설정 화면을 열어 GPS를 켜거나 끄도록 유도하는 방법을 단계별로 살펴봅니다.

GPS를 코드로 직접 제어할 수 없는 이유

보안과 사용자 동의 보호를 위해 안드로이드 4.4(API 레벨 19)부터는 일반 앱이 코드로 GPS를 직접 켜거나 끄는 것이 차단되어 있습니다. 따라서 앱은 Settings.ACTION_LOCATION_SOURCE_SETTINGS 인텐트를 사용해 시스템의 위치 설정 화면을 열어주고, 사용자가 직접 스위치를 조작하도록 안내하는 것이 공식적으로 권장되는 구현 방식입니다. 이번 예제도 바로 이 방식을 따릅니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계 — 레이아웃 작성 (res/layout/activity_main.xml)

GPS 상태를 표시할 TextView와 설정 화면으로 이동할 Button을 배치한 기본 레이아웃입니다.

<?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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/buttonGps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Enable/Disable GPS"/>
    <TextView
        android:id="@+id/textView"
        android:layout_centerInParent="true"
        android:layout_marginBottom="20dp"
        android:layout_above="@id/buttonGps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="Location Services" />
</RelativeLayout>

3단계 — 메인 액티비티 구현 (src/MainActivity.java)

LocationManager로 GPS 활성화 여부를 확인해 화면에 표시하고, 버튼 클릭 시 위치 설정 화면으로 이동합니다.

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button buttonGps;
    Context context;
    LocationManager locationManager;
    boolean GpsStatus;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        buttonGps = findViewById(R.id.buttonGps);
        context = getApplicationContext();
        CheckGPSStatus();
        buttonGps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });
}
  private void CheckGPSStatus() {
    locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(GpsStatus) {
            textView.setText("Location Services Is Enabled");
        } else {
            textView.setText("Location Services Is Disabled");
        }
    }
}

4단계 — 권한 선언 (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>

앱 실행 후 결과 확인

실제 안드로이드 기기를 컴퓨터에 연결했다고 가정하고 진행합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택해 앱을 실행합니다. 그러면 기기 화면에 아래와 같은 기본 화면이 나타납니다.

안드로이드에서 프로그래밍 방식으로 GPS 켜기/끄기 구현하는 방법

안드로이드에서 프로그래밍 방식으로 GPS 켜기/끄기 구현하는 방법

안드로이드에서 프로그래밍 방식으로 GPS 켜기/끄기 구현하는 방법


안드로이드에서 프로그래밍 방식으로 GPS 켜기/끄기 구현하는 방법

마무리 및 참고 사항

예제 코드는 구버전 support 라이브러리(android.support.v7.app.AppCompatActivity)를 사용하고 있습니다. 최신 프로젝트라면 AndroidX의 androidx.appcompat.app.AppCompatActivity로 교체하는 것이 좋습니다. 또한 onResume()에서 GPS 상태를 다시 확인하도록 하면, 사용자가 설정 화면에서 돌아왔을 때 변경된 위치 서비스 상태를 즉시 UI에 반영할 수 있어 더 완성도 높은 동작을 구현할 수 있습니다.