개요
이 튜토리얼에서는 AlarmManager를 활용하여 안드로이드 앱에서 지정한 미래의 특정 날짜와 시간에 알림(Notification)이 자동으로 표시되도록 예약하는 방법을 단계별로 소개합니다.
핵심 원리는 다음과 같습니다. 사용자가 DatePickerDialog로 날짜를 선택하면, 선택된 날짜 정보를 바탕으로 알림 객체를 생성하고 AlarmManager에 등록합니다. 이후 설정된 시간이 되면 시스템이 BroadcastReceiver를 통해 알림을 발송하는 구조입니다.
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"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select Date"
android:onClick="setDate"
android:padding="16dp" />
</RelativeLayout>3단계 — MainActivity 구현
src/MainActivity.java 파일에 아래 코드를 추가합니다. 이 클래스는 날짜 선택 처리, 알림 생성, 그리고 AlarmManager를 통한 예약 등록을 담당합니다.
package app.tutorialspoint.com.notifyme;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
Button btnDate;
final Calendar myCalendar = Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDate = findViewById(R.id.btnDate);
}
private void scheduleNotification(Notification notification, long 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);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, delay, 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();
}
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
public void setDate(View view) {
new DatePickerDialog(
MainActivity.this,
date,
myCalendar.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)
).show();
}
private void updateLabel() {
String myFormat = "dd/MM/yy"; // 원하는 날짜 형식으로 변경 가능
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
Date date = myCalendar.getTime();
btnDate.setText(sdf.format(date));
scheduleNotification(getNotification(btnDate.getText().toString()), date.getTime());
}
}주요 포인트:
- scheduleNotification() — 알림과 함께 PendingIntent를 생성한 뒤, AlarmManager에 등록하여 지정된 시간에 브로드캐스트가 전송되도록 합니다.
- getNotification() — 제목, 내용, 아이콘이 포함된 알림 객체를 빌드합니다.
- DatePickerDialog — 사용자가 연도, 월, 일을 직접 선택할 수 있는 대화상자를 제공합니다.
4단계 — 알림 발행자(BroadcastReceiver) 구현
src/MyNotificationPublisher.java 파일에 아래 코드를 추가합니다. 이 리시버는 알람이 울리는 순간 시스템으로부터 호출되어 실제 알림을 화면에 표시합니다.
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);
}
}안드로이드 8.0(오레오, API 26) 이상에서는 반드시 NotificationChannel을 생성해야 알림이 정상적으로 표시되므로, 위 코드에서 SDK 버전을 확인하여 채널을 생성하는 로직이 포함되어 있습니다.
5단계 — 매니페스트 설정
AndroidManifest.xml 파일에 아래 코드를 추가합니다. 진동 권한과 함께 리시버를 반드시 등록해야 합니다.
<?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 아이콘을 클릭하세요. 실행 옵션에서 본인의 모바일 기기를 선택하면, 앱이 설치되고 실행됩니다.
앱이 실행되면 화면에 기본 화면이 표시됩니다. 날짜 영역을 탭하여 미래의 날짜를 선택하면, 해당 날짜에 맞춰 알림이 예약되고 지정된 시점에 기기에 알림이 도착하는 것을 확인할 수 있습니다.