안드로이드 스튜디오 :: Java :: 알림 만들기(Notification)

Android/Java 2020.10.13 댓글 moonsu
728x90

본 문서는 안드로이드 개발자 가이드 를 토대로 작성되었습니다.

 

안드로이드 스튜디오에서 알림 만들기

 

1. 지원 라이브러리 추가

알림 콘텐츠를 시작하려면 NotificationCompat.Builder 객체를 사용해야한다. 하지만 그 전에 NotificationCompat 을 사용하는데 필요한 종속 항목이 포함되어 있는지 확인해야한다. (안드로이드 스튜디오로 제작한 대부분의 프로젝트는 아래 항목이 포함되어 있다.)

dependencies {
	// 작성일 기준이며, 버전은 계속 올라갈 수 있다.
        implementation 'androidx.appcompat:appcompat:1.2.0'
    }

 

2. 알림 설정

그림1. 제목과 텍스트가 있는 알림

NotificationCompat.Builder 객체를 사용해 컨텐츠와 채널 그리고 기본적인 설정을 해줘야한다.

static final String CHANNEL_ID = "channelId";

String textTitle = "Notification Title";
String textContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// NotificationCompat.Builder(context, "채널이름")
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

(1) setSmallIcon() : 알림 왼쪽 위에 보여지는 작은 아이콘, 필수 콘텐츠이다.

(2) setContentTitle() : 제목

(3) setContentText() : 본문

(4) setPriority() : 알림의 중요도. Android 7.1 이하 버전에서만 사용하며 Android8.0 이상의 경우 다른 방식(아래 설명)으로 중요도를 결정한다.

 

3. 채널 만들기

Android8.0 (API26) 이상에서는 호환성을 유지하기 위해 채널 ID를 제공해야한다. 이미 많은 스마트폰이 8.0 이상의 버전으로 사용되기에 사실상 필수라고 할 수 있다.

private void createNotificationChannel() {
    // Android8.0 이상인지 확인
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
        // 채널에 필요한 정보 제공
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        
        // 중요도 설정, Android7.1 이하는 다른 방식으로 지원한다.(위에서 설명)
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        
        // 채널 생성
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

알림을 게시하려면 위 코드가 필수로 실행되어야 한다. 채널이 한번 만들어지면 아무 작업도 실행되지 않기 때문에 앱이 시작하자마자, 그리고 반복적으로 호출하는 편이 안전한다.

 

4. 알림 탭 작업

알림을 클릭하면 어플이 실행되고, 알림에 연관된 페이지가 나타나는 것이 일반적이다. 이 작업을 하려면 PendingIntent 객체로 인텐트를 지정하여 setContentIntent() 에 전달해야 한다.

// 내가 보여주고자 하는 Activity 클래스 지정
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        
        // 위에서 정의한 pendingIntent 지정
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);
    

(1) setContentIntent() : pendingIntent 지정

(2) setAutoCancel() : 알림 자동 삭제, false로 설정하면 알림을 클릭해도 사라지지 않는다.

 

5. 알림

NotificationManagerCompat.notify() 를 호출해 고유ID와 위에서 미리 셋팅해둔 builder 를 전달한다.

static fianl int notificationId = 0;

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());

notificationId 는 알림을 업데이트하거나 삭제할 때 필요하다.

 

 

전체 소스코드

더보기
static final String CHANNEL_ID = "channelId";
static fianl int notificationId = 0;

@Override
protected void onCreate(Bundle savedInstanceState){
    String textTitle = "Notification Title";
    String textContent = "Lorem ipsum dolor sit.";
    
    // 채널 생성
    createNotificationChannel();

    // 내가 보여주고자 하는 Activity 클래스 지정
    Intent intent = new Intent(this, AlertDetails.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    // NotificationCompat.Builder(context, "채널이름")
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        
            // 위에서 정의한 pendingIntent 지정
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
            
    //호출
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, builder.build());
}
        
private void createNotificationChannel() {
    // Android8.0 이상인지 확인
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
        // 채널에 필요한 정보 제공
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        
        // 중요도 설정, Android7.1 이하는 다른 방식으로 지원한다.(위에서 설명)
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        
        // 채널 생성
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
728x90
반응형

댓글