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

Android에서 알림 채널 생성 및 관리하는 방법

Android에서 알림 채널 생성 및 관리하기

이 튜토리얼에서는 Android 앱에서 알림 채널(Notification Channel)을 생성하고 관리하는 방법을 단계별로 살펴봅니다. Android 8.0 오레오(API 26)부터는 모든 알림이 반드시 알림 채널에 할당되어야 하므로, 사용자가 알림의 소리·진동·중요도를 직접 제어할 수 있게 해주는 이 기능은 최신 Android 앱 개발에서 필수 요소입니다.

1단계 — Android Studio에서 새 프로젝트 생성

Android Studio를 실행한 후 File ⇒ New Project 메뉴로 이동하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.

2단계 — activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 버튼 하나로 화면을 구성하는 간단한 레이아웃입니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.constraint.ConstraintLayout
   xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: app = "https://schemas.android.com/apk/res-auto"
   xmlns: tools = "https://schemas.android.com/tools"
   android :layout_width = "match_parent"
   android :layout_height = "match_parent"
   android :padding = "16dp"
   tools :context = ".MainActivity" >
   <Button
      android :id = "@+id/btnCreateNotification"
      android :layout_width = "0dp"
      android :layout_height = "wrap_content"
      android :text = "Create notification"
      app :layout_constraintBottom_toBottomOf = "parent"
      app :layout_constraintEnd_toEndOf = "parent"
      app :layout_constraintStart_toStartOf = "parent"
      app :layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

3단계 — 사운드 파일 추가

알림음으로 사용할 사운드 파일(예: quite_impressed.mp3)을 res/raw 폴더에 넣습니다. raw 폴더가 없다면 res 디렉터리 아래에 새로 생성하면 됩니다.

Android에서 알림 채널 생성 및 관리하는 방법

4단계 — MainActivity.java 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 이 코드는 버튼을 클릭할 때마다 알림 채널을 생성하고, 채널에 맞는 알림을 발송하는 역할을 합니다.

package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.content.ContentResolver ;
import android.content.Context ;
import android.graphics.Color ;
import android.media.AudioAttributes ;
import android.net.Uri ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
import android.view.View ;
import android.widget.Button ;
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 ) ;
      Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;
      btnCreateNotification.setOnClickListener( new View.OnClickListener() {
         @Override
         public void onClick (View v) {
            Uri sound = Uri. parse (ContentResolver. SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/quite_impressed.mp3" ) ;
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this,
               default_notification_channel_id )
                .setSmallIcon(R.drawable. ic_launcher_foreground )
                .setContentTitle( "Test" )
                .setSound(sound)
                .setContentText( "Hello! This is my first push notification" );
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;
            if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
               AudioAttributes audioAttributes = new AudioAttributes.Builder()
                  .setContentType(AudioAttributes. CONTENT_TYPE_SONIFICATION )
                  .setUsage(AudioAttributes. USAGE_ALARM )
                  .build() ;
               int importance = NotificationManager. IMPORTANCE_HIGH ;
               NotificationChannel notificationChannel = new
                  NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
               notificationChannel.enableLights( true ) ;
               notificationChannel.setLightColor(Color. RED ) ;
               notificationChannel.enableVibration( true ) ;
               notificationChannel.setVibrationPattern( new long []{ 100 , 200 , 300 , 400 , 500 , 400 , 300 , 200 , 400 }) ;
               notificationChannel.setSound(sound , audioAttributes) ;
               mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
               assert mNotificationManager != null;
               mNotificationManager.createNotificationChannel(notificationChannel) ;
            }
            assert mNotificationManager != null;
            mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build()) ;
         }
      }) ;
   }
}

코드 핵심 포인트:

  • 버튼 클릭 시 raw 폴더의 mp3 파일을 리소스 URI로 변환하여 알림 사운드로 지정합니다.
  • Android 8.0(API 26) 이상에서만 실행되는 조건문 안에서 NotificationChannel 객체를 생성합니다.
  • 채널에는 IMPORTANCE_HIGH 중요도, 빨간색 LED 알림등, 사용자 지정 진동 패턴, 알람 용도의 AudioAttributes 사운드가 설정됩니다.
  • 마지막으로 NotificationManager를 통해 채널을 등록하고 알림을 발송합니다.

5단계 — AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "https://schemas.android.com/apk/res/android"
   package = "app.tutorialspoint.com.notifyme" >
   <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>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 실행(Run) 아이콘을 클릭하고, 옵션 목록에서 모바일 기기를 선택하세요. 그러면 모바일 기기에 아래와 같은 기본 화면이 표시됩니다.

Android에서 알림 채널 생성 및 관리하는 방법

화면의 Create notification 버튼을 누르면, 설정한 알림 채널의 속성(사운드, 진동 패턴, LED 색상)이 적용된 알림이 즉시 표시됩니다. 이후에는 사용자가 시스템 설정에서 해당 채널의 동작 방식을 자유롭게 변경할 수 있습니다.