안드로이드에서 프로그래밍 방식으로 GPS 활성화/비활성화하기
이 튜토리얼에서는 안드로이드 앱에서 GPS(위치 서비스)의 현재 상태를 확인하고, 버튼을 누르면 위치 설정 화면으로 이동해 사용자가 GPS를 직접 켜거나 끌 수 있도록 구현하는 방법을 단계별로 알아봅니다.
보안 정책상 앱이 사용자 동의 없이 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/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:text="Click Here to Enable Disable GPS location service!" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="132dp"
android:gravity="center"
android:text="location service Stauts Shows Here"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
3단계 — MainActivity.java 작성하기
다음 코드를 src/MainActivity.java에 추가합니다. 핵심 로직은 두 가지입니다. 첫째, LocationManager.isProviderEnabled(GPS_PROVIDER) 메서드로 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 {
Button button;
Context context;
Intent intent1;
TextView textview;
LocationManager locationManager;
boolean GpsStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
textview = (TextView) findViewById(R.id.textView1);
context = getApplicationContext();
CheckGpsStatus();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 위치 설정 화면으로 이동
intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
}
});
}
public void CheckGpsStatus() {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
assert locationManager != null;
GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (GpsStatus == true) {
textview.setText("GPS Is Enabled");
} else {
textview.setText("GPS Is Disabled");
}
}
}
4단계 — 매니페스트에 권한 추가하기
GPS 상태를 조회하려면 위치 권한 선언이 반드시 필요합니다. 다음 코드를 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 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 나타납니다.



추가 팁: 더 나은 사용자 경험을 위한 최신 방식
Android 10(API 29) 이상에서는 위치 권한 정책이 한층 엄격해졌습니다. 설정 화면으로 이동시키는 대신 Google Play Services의 LocationSettingsRequest와 SettingsClient를 활용하면, 앱 내 대화상자 한 번으로 사용자에게 GPS 활성화를 유도할 수 있어 이탈률을 줄이고 UX를 크게 개선할 수 있습니다.