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

BroadcastReceiver로 Android 예약 알림 만드는 방법 – 단계별 구현 가이드

개요

이 글에서는 BroadcastReceiverAlarmManager를 조합하여 Android 앱에서 일정 시간이 지난 후 알림(Notification)이 자동으로 표시되도록 구현하는 방법을 단계별로 소개합니다. 메뉴에서 5초, 10초, 30초 중 하나를 선택하면 그만큼의 지연 시간 후에 알림이 울리는 예제입니다.

작동 원리 간단 정리

  • MainActivity: 사용자가 선택한 지연 시간만큼 AlarmManager에 알림 발행을 예약합니다.
  • PendingIntent: 예약된 시점에 브로드캐스트를 전송하는 역할을 합니다.
  • MyNotificationPublisher: 브로드캐스트를 수신(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

옵션 메뉴에 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단계 − src/MainActivity.java

메뉴 항목 선택 시 AlarmManager로 알림 발행 시점을 예약하는 MainActivity 코드입니다. scheduleNotification() 메서드가 PendingIntent를 생성해 AlarmManager에 등록하고, getNotification() 메서드가 알림 객체를 빌드합니다.

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) {
      // Inflate the menu; this adds items to the action bar if it is present.
      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() ;
   }
}

5단계 − src/MyNotificationPublisher.java

AlarmManager가 발생시키는 브로드캐스트를 수신하여 실제로 알림을 게시하는 BroadcastReceiver 클래스입니다. Android 8.0(Oreo, API 26) 이상에서는 반드시 알림 채널(NotificationChannel)을 생성해야 하므로 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

매니페스트 파일에 진동(VIBRATE) 권한과 알림 발행용 리시버를 등록합니다. 리시버가 등록되어 있어야 AlarmManager가 보낸 브로드캐스트를 앱이 받을 수 있습니다.

<? 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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 옵션 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

BroadcastReceiver로 Android 예약 알림 만드는 방법 – 단계별 구현 가이드

BroadcastReceiver로 Android 예약 알림 만드는 방법 – 단계별 구현 가이드

참고 사항

  • 이 예제는 구버전 Support Library(android.support.*)를 사용합니다. 최신 프로젝트라면 AndroidX(androidx.core.app.NotificationCompat, androidx.appcompat.app.AppCompatActivity)로 마이그레이션하는 것이 좋습니다.
  • Android 13(API 33) 이상에서는 알림 표시를 위해 POST_NOTIFICATIONS 런타임 권한 요청이 추가로 필요합니다.
  • 정확한 시간에 알림을 띄우려면 API 31(S) 이상에서 SCHEDULE_EXACT_ALARM 권한과 setExactAndAllowWhileIdle() 사용을 검토하세요.