본문 바로가기
안드로이드 자바

[JAVA][Android] 알림(Notification) 기능 만들기

by teamnova 2021. 5. 2.

Notification 

Notification(알림)은 앱이 forground에서 실행 상태가 아니여도 사용자에게 정보를 제공할 수 있는 UI형태 입니다. 쉽게 말해 카카오톡의 메시지 알림 메시지를 떠올리시면 이해가 되시겠죠?

 

알림을 만들기 전에 우선 채널에 대한 이해가 필요합니다.

왜냐하면 안드로이드 8.0 Oreo (2017년 8월 발표) 이상부터는 Notification Channel을 필수적으로 만들어줘야 하기 때문인데요


Notification Channel

Notification을 여러가지 용도로 나누어서 관리할 수 있게 만들어 주고 사용자가 직접 각 채널별로 알림 중요도나 기타 설정을 변경할 수 있습니다. 

 

Oreo이전에는 Notification을 앱 단위로 운영했다면 지금은 앱 하위에 Channel이 존재한다고 생각하면 됩니다.

 

한마디로 알림의 종류를 세분화 해서 다룬다는 말인데요. 이게 왜 필요한지는 차근차근 알아봅시다. 

 


<activity_main.xml>

 

 

기본 레이아웃 화면입니다.

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/design_default_color_primary"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="212dp"
        android:src="@drawable/stickcode"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/notify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notify Me!"
        android:textColor="@color/black"
        android:backgroundTint="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:layout_constraintVertical_bias="0.335" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

이젠 본격적으로 시작해 볼까요?

 

전체적이 순서를 정하고 진행하겠습니다.

 

1. NotificationManager , Notification Channel 생성

2. Notification Builder 생성

3. NotificationManager 로 Notification 전달

 

 

1. NotificationManager , Notification Channel 생성

 

 

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Channel에 대한 id 생성 : Channel을 구부하기 위한 ID 이다.
        private static final String CHANNEL_ID = "채널 ID를 입력하세요";
        // Channel을 생성 및 전달해 줄 수 있는 Manager 생성
        private NotificationManager mNotificationManager;

         //notification manager 생성
         mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
          // 기기(device)의 SDK 버전 확인 ( SDK 26 버전 이상인지 - VERSION_CODES.O = 26)
         if(android.os.Build.VERSION.SDK_INT
                        >= android.os.Build.VERSION_CODES.O){
                    //Channel 정의 생성자( construct 이용 )
                    NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,"Test Notification",mNotificationManager.IMPORTANCE_HIGH);
                    //Channel에 대한 기본 설정
                    notificationChannel.enableLights(true);
                    notificationChannel.enableVibration(true);
                    notificationChannel.setDescription("Notification from Mascot");
                    // Manager을 이용하여 Channel 생성
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
 }

 

 

변수 PRIMAY_CHANNEL_ID는 CHANNEL을 구분하기 위한 ID 입니다

 

Notification을 생성 및 전달할때 NotificationManager가 필요해서 변수 생성

 

스틱코드로 생성된 변수들은 바깥쪽으로 빼주는건 아시죠?

 

채널을 생성하면서 다양한 옵션들을 설정할 수 있는데요 저희는 라이트표시 설정과 진동 설정을 해주었습니다.

 

보다더 다양한 설정을 해주고 싶다면 안드로이드 공식문서를 참고해주세요

 

https://developer.android.com/reference/android/app/NotificationChannel

 

NotificationChannel  |  Android 개발자  |  Android Developers

 

developer.android.com


2. Notification Builder 생성

Builder의 역할은 Notification을 생성해주는 것입니다.

여기서 주의할 것은 Notification을 생성할 때 Notification.Compat class를 사용하는 것입니다. 

 

 // Notivication에 대한 ID 생성
        private static final int NOTIFICATION_ID = 0;

        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentTitle("Stickcode")
                        .setContentText("스틱코드에 오신걸 환영합니다.")
                        .setSmallIcon(R.drawable.stickcode);

Notification에도 다양한 설정을 할 수 있는데요 저희는 간단히 제목과 내용 그리고 아이콘을 넣어주었습니다.

 

setContentTitle() : 알림 제목 설정

 

setContentText() : 알림 내용 설정

 

setSmallIcon() : 알림 아이콘 설정

 

보다 더 다양한 설정을 해주고 싶다면 안드로이드 공식문서를 참고해주세요 (영어로 작성되었다고 겁먹지 마시고 차근차근 보면 쉬운 단어로 친철하게 설명해주고 있어요 ^^)

 

https://developer.android.com/reference/android/app/Notification.Builder

 

Notification.Builder  |  Android 개발자  |  Android Developers

 

developer.android.com

3. NotificationManager 로 Notification 전달

이제 마지막 단계로 위에서 만들어준 notifiction을 NotificationManager로 전달하겠습니다.

 

 

 mNotificationManager.notify(NOTIFICATION_ID, notifyBuilder.build());

 

이 코드는 버튼을 눌러줬을때 호출해줘야겠죠? 

 

버튼에 이벤트를 등로해줍니다.

 

btn_notify = findViewById(R.id.notify);
        
btn_notify.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         mNotificationManager.notify(NOTIFICATION_ID, notifyBuilder.build());

     }
 });

 

 

버튼을 눌러주면 저희가 작성한 notification이 화면 상단에 나타납니다.

 

 

 

 

알림이 나타나는걸 보실수 있는데요

 

카톡의 알림처럼 터치를 해도 아무 변화가 없습니다. 

 

조금만 더 손을 봐 볼까요?

 

알림을 클릭하면 다른 화면으로 이동하고 싶습니다. (카톡처럼)

 

그러면 이동할 화면도 Intent 겠죠? 

 

정확히 말하면 Intent를 직접 사용하지 못하고 PendingIntent를 사용합니다. 

 

먼저 새로운 Activity를 생성합니다.


<activity_pending_activity.xml>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/design_default_color_primary"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="208dp"
        android:src="@drawable/stickcode"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="WELCOME TO STICKODE"
        android:textColor="@color/white"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:layout_constraintVertical_bias="0.273" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

Intent notificationIntent = new Intent(this, PendingAcitivty.class);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, notificationIntent, PendingInte

 

그리고 마지막으로 Notification Builder 에 설정해줍니다.

 

 NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentTitle("Stickode")
                        .setContentText("스틱코드에 오신걸 환영합니다.")
                        .setSmallIcon(R.drawable.stickcode)
                        .setContentIntent(notificationPendingIntent) //추가된 부분
                        .setAutoCancel(true); //notification을 탭 했을경우 notification을 없앤다.

 

다시 앱을 실행하고 버튼을 누르면 Notification이 나타납니다.

 

이제는 Notification을 터치하면 저희가 만들어준 새로운 화면으로 이동하는것을 보실수 있습니다.