Android 브로드캐스트 리시버로 알림 시작 및 중지하기
이 튜토리얼에서는 브로드캐스트 리시버(BroadcastReceiver)를 사용해 Android 알림을 동적으로 표시하고 제거하는 방법을 단계별로 살펴봅니다. 예제에서는 USB 연결 상태 변화를 알려주는 시스템 브로드캐스트(USB_STATE)를 수신하여, 알림을 띄우거나 취소하는 로직을 구현합니다.
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project 메뉴로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계: activity_main.xml 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이 예제에서는 별도의 UI 요소 없이 빈 RelativeLayout만 사용합니다.
<?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:padding="16dp"
tools:context=".MainActivity" />
3단계: MainActivity 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다. 기본적인 AppCompatActivity를 상속받는 일반적인 액티비티입니다.
package app.tutorialspoint.com.notifyme;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
4단계: USBStateReceiver 작성
src/USBStateReceiver.java 파일에 아래 코드를 추가합니다. 이 리시버가 예제의 핵심 부분입니다. onReceive() 콜백에서 NotificationCompat.Builder로 알림을 생성하며, Android 8.0(API 26) 이상에서는 반드시 알림 채널(NotificationChannel)을 먼저 생성해야 한다는 점에 유의하세요. connected 플래그 값에 따라 알림을 표시(notify())하거나 제거(cancel())합니다.
package app.tutorialspoint.com.notifyme;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class USBStateReceiver extends BroadcastReceiver {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
boolean connected = true;
@SuppressLint("UnsafeProtectedBroadcastReceiver")
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, default_notification_channel_id);
builder.setContentTitle("USB - Notification");
String action = intent.getAction();
Log.e("USB", action);
assert action != null;
builder.setContentText("Connected");
builder.setSmallIcon(R.drawable.ic_launcher_foreground);
builder.setAutoCancel(true);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
assert notificationManager != null;
if (connected) {
notificationManager.notify(1, notification);
connected = false;
} else {
notificationManager.cancel(1);
connected = true;
}
}
}
5단계: AndroidManifest.xml 설정
AndroidManifest.xml 파일에 아래 코드를 추가합니다. <receiver> 태그 안에 인텐트 필터를 등록하여 android.hardware.usb.action.USB_STATE 브로드캐스트를 수신하도록 선언합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<uses-permission android:name="android.permission.VIBRATE" />
<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>
<receiver android:name=".USBStateReceiver">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하고 배포할 모바일 기기를 선택합니다. 그다음 기기 화면에서 결과를 확인하면 됩니다.
