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

안드로이드 알림 예약 방법: AlarmManager로 지연 알림 구현하기


앱이 실행 중이 아니더라도 지정한 시간에 사용자에게 알림을 전달하고 싶다면 어떻게 해야 할까요? 이 글에서는 안드로이드의 AlarmManagerBroadcastReceiver를 활용해 알림을 예약하는 방법을 단계별로 살펴봅니다. 예제에서는 메뉴에서 5초, 10초, 30초 중 하나를 선택하면 해당 시간이 지난 뒤 알림이 표시되도록 구현합니다.

핵심 개념 미리 보기

코드를 살펴보기 전에 이 예제에서 사용하는 세 가지 핵심 컴포넌트를 이해하면 훨씬 쉽게 따라올 수 있습니다.

  • AlarmManager : 앱의 생명주기와 관계없이 지정한 시점에 작업을 실행하도록 예약해 주는 시스템 서비스입니다.
  • PendingIntent : 나중에 시스템이 대신 실행해 줄 인텐트를 감싸는 객체입니다.
  • BroadcastReceiver : 알람이 울리는 시점에 시스템이 호출하는 수신자로, 실제 알림을 게시하는 역할을 담당합니다.

1단계 : 새 프로젝트 생성

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

2단계 : 메인 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?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단계 : 옵션 메뉴 정의

res/menu/main_menu.xml 파일을 만들고, 알림 지연 시간을 선택할 수 있는 메뉴 항목 3개(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>

4단계 : MainActivity 구현

src/MainActivity에 아래 코드를 작성합니다. 메뉴 항목을 선택하면 scheduleNotification() 메서드가 호출되어 AlarmManager에 알림 발행 작업을 예약합니다.

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();
    }
}

scheduleNotification() 메서드의 동작 흐름은 다음과 같습니다.

  • MyNotificationPublisher를 대상으로 하는 Intent를 만들고 알림 ID와 Notification 객체를 첨부합니다.
  • PendingIntent.getBroadcast()로 브로드캐스트용 PendingIntent를 생성합니다.
  • SystemClock.elapsedRealtime()에 지연 시간을 더해 목표 시각을 계산합니다.
  • alarmManager.set()에 ELAPSED_REALTIME_WAKEUP 타입으로 등록해, 기기가 절전 모드일 때도 알림이 울리도록 합니다.

5단계 : MyNotificationPublisher 구현

src/MyNotificationPublisher에 BroadcastReceiver를 상속받는 클래스를 작성합니다. onReceive()가 호출되면 Intent에 담겨 있던 Notification을 꺼내 NotificationManager로 게시합니다. Android 8.0(오레오) 이상에서는 알림 채널을 먼저 생성해야 하므로 SDK 버전을 확인하는 코드가 포함되어 있습니다.

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);
    }
}

6단계 : 매니페스트 설정

AndroidManifest.xml에 진동 권한과 리시버를 등록합니다. 리시버를 선언하지 않으면 알람이 발생해도 onReceive()가 호출되지 않으므로 반드시 추가해야 합니다.

<?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 아이콘을 클릭해 앱을 실행합니다. 기기를 선택하면 앱이 설치·실행되고, 화면 오른쪽 위 점 세 개 메뉴에서 원하는 지연 시간을 고르면 설정한 시간이 지난 뒤 아래와 같이 알림이 표시됩니다.

안드로이드 알림 예약 방법: AlarmManager로 지연 알림 구현하기

안드로이드 알림 예약 방법: AlarmManager로 지연 알림 구현하기

마무리 및 참고 사항

이 예제는 set() 메서드를 사용했기 때문에 지정한 시간에 딱 한 번 알림을 발송합니다. 주기적으로 반복되는 알림이 필요하다면 setRepeating() 또는 setInexactRepeating()을 사용하면 됩니다. 또한 Android 12(S) 이상에서는 정확한 알람을 위해 SCHEDULE_EXACT_ALARM 권한이 필요할 수 있고, 제조사별 배터리 최적화 정책에 따라 알람이 지연될 수 있다는 점도 함께 고려하시기 바랍니다.