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

Android에서 로컬 알림을 예약하는 방법 – AlarmManager 활용 완벽 가이드

안드로이드 앱을 개발하다 보면 사용자가 지정한 시간에 알림(Notification)을 자동으로 띄워야 하는 경우가 많습니다. 예를 들어 리마인더, 타이머, 할 일 알림 등이 대표적입니다. 이번 튜토리얼에서는 AlarmManagerBroadcastReceiver를 활용해 특정 시간(5초, 10초, 30초 후)에 로컬 알림을 예약하고 발송하는 방법을 단계별로 살펴보겠습니다.

핵심 개념 정리

구현에 앞서 사용될 주요 컴포넌트를 간단히 짚고 넘어가겠습니다.

  • AlarmManager: 앱이 실행 중이 아니더라도 지정한 시점에 작업을 실행하도록 예약하는 시스템 서비스입니다.
  • PendingIntent: 예약된 시점에 시스템이 대신 실행할 인텐트를 담아두는 객체입니다.
  • BroadcastReceiver: 알람이 울리는 순간 브로드캐스트를 수신하여 실제 알림을 발송하는 역할을 합니다.
  • NotificationChannel: Android 8.0(오레오) 이상에서는 반드시 채널을 생성해야 알림이 표시됩니다.

Step 1 – 새 프로젝트 생성

Android Studio에서 File → New Project를 선택한 뒤, 빈 액티비티(Empty Activity) 템플릿으로 새 프로젝트를 생성하고 필요한 정보를 모두 입력합니다.

Step 2 – activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이 예제에서는 화면에 별다른 UI 없이 옵션 메뉴만 사용하므로 레이아웃은 기본 구조만 유지합니다.

<?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" />

Step 3 – 옵션 메뉴(main_menu.xml) 정의

res/menu/main_menu.xml 파일을 생성하고, 알림 지연 시간을 선택할 수 있는 세 개의 메뉴 항목(5초, 10초, 30초)을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_5"
        app:showAsAction="never"
        android:title="5 seconds" />
    <item
        android:id="@+id/action_10"
        app:showAsAction="never"
        android:title="10 seconds" />
    <item
        android:id="@+id/action_30"
        app:showAsAction="never"
        android:title="30 seconds" />
</menu>

Step 4 – MainActivity 구현

src/MainActivity.java에 아래 코드를 작성합니다. 메뉴 선택 시 scheduleNotification() 메서드가 호출되어 AlarmManager에 알림 발행 작업을 예약하고, getNotification() 메서드가 실제 표시될 Notification 객체를 생성합니다.

package app.tutorialspoint.com.notifyme;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_5:
                scheduleNotification(getNotification("5 second delay"), 5000);
                return true;
            case R.id.action_10:
                scheduleNotification(getNotification("10 second delay"), 10000);
                return true;
            case R.id.action_30:
                scheduleNotification(getNotification("30 second delay"), 30000);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private void scheduleNotification(Notification notification, int delay) {
        Intent notificationIntent = new Intent(this, MyNotificationPublisher.class);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, 1);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        long futureInMillis = SystemClock.elapsedRealtime() + delay;
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        assert alarmManager != null;
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    }
    private Notification getNotification(String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, default_notification_channel_id);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        return builder.build();
    }
}

여기서 주목할 부분은 SystemClock.elapsedRealtime()입니다. 부팅 이후 경과된 실제 시간을 기준으로 하므로 딥슬립 상태에서도 정확하게 동작하며, ELAPSED_REALTIME_WAKEUP 플래그를 사용하면 기기가 절전 모드일 때도 화면을 깨워 알림을 전달할 수 있습니다.

Step 5 – MyNotificationPublisher(BroadcastReceiver) 구현

src/MyNotificationPublisher.java를 생성합니다. 알람이 트리거되면 이 리시버의 onReceive()가 호출되어, Android 8.0 이상에서는 먼저 알림 채널을 생성한 뒤 알림을 발송합니다.

package app.tutorialspoint.com.notifyme;
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 static app.tutorialspoint.com.notifyme.MainActivity.NOTIFICATION_CHANNEL_ID;
public class MyNotificationPublisher extends BroadcastReceiver {
    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        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);
        }
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        assert notificationManager != null;
        notificationManager.notify(id, notification);
    }
}

Step 6 – AndroidManifest.xml 설정

마지막으로 AndroidManifest.xml에 진동 권한과 리시버를 등록합니다. BroadcastReceiver는 반드시 매니페스트에 선언되어야 시스템이 알람 발생 시 해당 컴포넌트를 찾아 실행할 수 있습니다.

<?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=".MyNotificationPublisher" />
    </application>
</manifest>

앱 실행 및 결과 확인

실제 안드로이드 기기를 컴퓨터에 연결한 뒤, Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 버튼을 클릭합니다. 배포할 기기로 연결된 스마트폰을 선택하면 앱이 설치·실행됩니다.

앱이 실행되면 오른쪽 상단의 옵션 메뉴(⋮)를 열어 5 seconds, 10 seconds, 30 seconds 중 하나를 선택하세요. 선택한 시간이 지난 후 다음과 같이 예약된 알림이 상태바에 나타나는 것을 확인할 수 있습니다.

Android에서 로컬 알림을 예약하는 방법 – AlarmManager 활용 완벽 가이드

Android에서 로컬 알림을 예약하는 방법 – AlarmManager 활용 완벽 가이드

마무리 및 참고 사항

이처럼 AlarmManager와 BroadcastReceiver를 조합하면 앱이 포그라운드에 있지 않아도 원하는 시점에 알림을 전달할 수 있습니다. 다만 몇 가지 유의할 점이 있습니다.

  • Doze 모드와 앱 스탠바이: Android 6.0 이상에서는 배터리 최적화로 인해 알람이 지연될 수 있으며, 정확한 실행이 필요하다면 setExactAndAllowWhileIdle() 같은 API를 고려해야 합니다.
  • 기기 재부팅 시 알람 소멸: AlarmManager로 등록한 알람은 재부팅 후 사라지므로, BOOT_COMPLETED 브로드캐스트를 수신해 알람을 다시 등록하는 로직이 필요합니다.
  • Android 12(S) 이상: 정확한 알람(exact alarm)을 사용하려면 SCHEDULE_EXACT_ALARM 권한 선언이 필요할 수 있습니다.

이 예제를 바탕으로 반복 알림(setRepeating())이나 특정 날짜·시간 지정 알림으로 확장하면 실무에서 바로 활용할 수 있는 리마인더 기능을 만들 수 있습니다.