[Android] 기본 Notification 생성 ( ft. NotificationCompat )

개요

먼저 앱 최초 실행시에 NotifiactionChannel을 설정해주어야 한다.

createNotificationChannel()

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(CHANNEL_ID, 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 = getContext().getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

다음과 같은 코드로 notifiaction을 띄우고, 클릭시 앱을 시작하도록 한다.

Intent intent = new Intent(getBridge().getContext(), getBridge().getActivity().getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getBridge().getContext(), 0, intent, 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(), CHANNEL_ID)
       .setSmallIcon(android.R.mipmap.sym_def_app_icon)
       .setContentTitle("이상징후 발생")
       .setStyle(new NotificationCompat.BigTextStyle().bigText("큰 텍스트 제목"))
       .setContentIntent(pendingIntent)
       .setPriority(NotificationCompat.PRIORITY_HIGH);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext());

// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build());