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

Android에서 비행기 모드 켜짐/꺼짐 상태 감지하는 방법

이 글에서는 Android 앱에서 비행기 모드(Airplane Mode)가 켜져 있는지 꺼져 있는지 감지하는 방법을 단계별로 알아봅니다. 설정값을 읽어오는 간단한 코드 몇 줄만으로도 현재 기기의 비행기 모드 상태를 확인할 수 있습니다.

1단계: 새 프로젝트 생성

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

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

res/layout/activity_main.xml에 아래 코드를 추가합니다. 화면 중앙에 비행기 모드 상태를 표시할 TextView 하나를 배치하는 구조입니다.

<?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">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center" />
</RelativeLayout>

3단계: MainActivity에 비행기 모드 확인 로직 추가

src/MainActivity.java에 아래 코드를 추가합니다. 핵심은 Settings.Global.AIRPLANE_MODE_ON 값을 읽어와 0인지 아닌지 판별하는 것입니다.

package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        checkAirplaneMode();
    }
    private void checkAirplaneMode() {
        if (isAirplaneModeOn(getApplicationContext())) {
            textView.setText("Airplane Mode is Enabled");
        } else {
            textView.setText("Airplane Mode is Disabled");
        }
    }
    private static boolean isAirplaneModeOn(Context context) {
        return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}

코드 설명

  • isAirplaneModeOn(): ContentResolver를 통해 시스템 설정 값을 조회하여 비행기 모드가 활성화되어 있으면 true를 반환합니다.
  • checkAirplaneMode(): 반환된 값에 따라 TextView에 "비행기 모드 사용 중" 또는 "비행기 모드 꺼짐" 문구를 표시합니다.

4단계: AndroidManifest.xml 작성

androidManifest.xml에 아래 코드를 추가합니다. 이 예제에서는 별도의 권한 선언 없이도 설정값을 읽을 수 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <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 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 현재 비행기 모드 상태가 표시됩니다.

Android에서 비행기 모드 켜짐/꺼짐 상태 감지하는 방법

추가 팁: 비행기 모드 변경 실시간 감지하기

앱이 실행되는 도중에 사용자가 비행기 모드를 전환하는 경우를 처리하려면, BroadcastReceiver를 등록하고 ACTION_AIRPLANE_MODE_CHANGED 인텐트를 수신하면 됩니다. 이렇게 하면 설정이 변경될 때마다 UI를 즉시 갱신할 수 있어 더 완성도 높은 앱을 만들 수 있습니다.