이 예제는 안드로이드(Android)에서 기기가 현재 비행기 모드인지 아닌지를 확인하는 방법을 보여줍니다. 브로드캐스트 리시버(BroadcastReceiver)를 활용하면 비행기 모드가 켜지거나 꺼질 때마다 실시간으로 상태 변화를 감지할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 새 프로젝트를 만듭니다. 메뉴에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
xmlns:app = "https://schemas.android.com/apk/res-auto"
xmlns:tools = "https://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>위 코드에서는 기기의 상태를 화면에 표시하기 위해 TextView를 사용했습니다.
3단계 — MainActivity 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import static android.os.BatteryManager.ACTION_CHARGING;
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.text);
}
@Override
protected void onStop() {
super.onStop();
MainActivity.this.unregisterReceiver(mMessageReceiver);
}
@Override
protected void onResume() {
super.onResume();
MainActivity.this.registerReceiver(mMessageReceiver, new IntentFilter("android.intent.action.AIRPLANE_MODE"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
textView.setText("Device is airplane mode");
}
};
}코드 설명
핵심 동작 방식은 다음과 같습니다.
- onResume() — 액티비티가 화면에 나타날 때
android.intent.action.AIRPLANE_MODE액션을 수신하는 브로드캐스트 리시버를 등록합니다. - onStop() — 액티비티가 더 이상 보이지 않으면 리시버 등록을 해제하여 메모리 누수를 방지합니다.
- onReceive() — 비행기 모드 상태가 변경되면 시스템이 브로드캐스트를 전송하고, 이때 TextView에 해당 상태를 표시합니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기의 기본 화면에 아래와 같은 결과가 표시됩니다.
