들어가며

안드로이드의 가장 기본적인 알림을 사용해보자. 아마 프로젝트 하다가 어떻게 쓰는지 궁금한 사람들이 검색을 했을 테니 최대한 간결하게 코드를 통해 설명하겠다. 코드를 세세하게 찾아보고 싶은 사람은 android developers의 문서를 참조하기 바란다.

 

사용방법

1. Notification Channel만들기

각 어플리케이션에서 Notification알림을 실행하려면 우선 채널을 만들어야한다. 

아래 코드를 복사해서 MainActivity에 추가하고 onCreate에서 해당 함수를 호출해주자

*채널명과 설명은 본인 어플리케이션에 맞게 설정해주자

private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "공지사항 채널";
            String description = "공지사항 채널";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("공지사항 채널", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

2. 새로운 Notification을 만들고 이를 NotificationManager에 추가해주자

URLData.activity는 호출을 위한 액티비티 Context를 추가해주면된다.(ex MainActivity.this)

플래그를 설정해주고 PendingIntent를 호출하자.

builder를 만들 때 setContentIntent에서 이를 추가하고 Notification을 위한 다른 정보를 추가해주자(제목, 내용 등)

마지막으로 액티비티에서 NotificationManagerCompat를 호출해주고 notify로 builder로 만든 Notification을 추가해주면 끝이다.

Intent intent = new Intent(URLData.activity, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(URLData.activity, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(URLData.activity, "공지사항 채널")
                                    .setSmallIcon(R.drawable.app_icon)
                                    .setContentTitle(urlDataList.get(index).urlName)
                                    .setContentText("새로운 공지사항이 등록되었습니다!!")
                                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                    .setContentIntent(pendingIntent)
                                    .setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(URLData.activity);
notificationManager.notify('1', builder.build());

+ Recent posts