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

Android에서 NotificationCompat.Builder를 사용해 알림(Notification) 만드는 방법

안드로이드 알림(Notification)이란?

NotificationCompat.Builder를 본격적으로 다루기 전에, 먼저 안드로이드에서 '알림'이 무엇인지 이해할 필요가 있습니다. 알림은 액션 바(상태 표시줄)에 표시되는 메시지 형태의 시스템 UI 요소로, 사용자가 앱을 열지 않고도 중요한 정보를 즉시 확인할 수 있게 해줍니다. 대표적인 예로 부재중 전화 알림을 들 수 있습니다.

이 예제에서는 안드로이드 앱에 알림 기능을 통합하는 방법을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 만들기

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

2단계: 레이아웃 파일 작성

아래 코드를 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"
    tools:context = ".MainActivity">
    <Button
        android:id = "@+id/button"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Click"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

3단계: MainActivity 작성

다음으로 src/MainActivity.java에 아래 코드를 추가합니다. 이 코드는 버튼 클릭 시 알림 채널을 생성하고, NotificationCompat.Builder를 통해 알림을 발송하는 전체 흐름을 담고 있습니다.

package com.example.andy.myapplication;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=findViewById(R.id.button);
        button.setOnClickListener(this);
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
            notificationDialog();
            break;
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void notificationDialog() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "tutorialspoint_01";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
            // 알림 채널 설정
            notificationChannel.setDescription("Sample Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notificationBuilder.setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setTicker("Tutorialspoint")
        //.setPriority(Notification.PRIORITY_MAX)
        .setContentTitle("sample notification")
        .setContentText("This is sample notification")
        .setContentInfo("Information");
        notificationManager.notify(1, notificationBuilder.build());
    }
}

주요 코드 설명

위 코드의 핵심 포인트를 정리하면 다음과 같습니다.

알림 채널(Notification Channel): Android 8.0(Oreo, API 26)부터는 모든 알림을 반드시 채널에 할당해야 합니다. 코드에서는 SDK 버전을 확인해 O 이상일 경우에만 채널을 생성하며, 채널 설명, LED 알림 색상(빨간색), 진동 패턴 등을 함께 구성합니다.

NotificationCompat.Builder: 호환성 라이브러리가 제공하는 빌더 클래스로, 다양한 안드로이드 버전에서 일관된 알림 동작을 보장합니다. 자동 취소(autoCancel), 제목, 본문 텍스트, 작은 아이콘 등 필수 속성을 체이닝 방식으로 설정한 뒤 notify() 메서드로 알림을 게시합니다.

앱 실행 및 결과 확인

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

화면에 나타난 버튼을 클릭하면 아래와 같이 알림이 정상적으로 출력되는 것을 확인할 수 있습니다.