sggnology
하늘속에서IT
sggnology
전체 방문자
오늘
어제
  • 분류 전체보기 (83)
    • Algorithm (31)
      • Programmers (27)
      • Baekjoon (4)
    • WIKI (4)
      • VirtualBox (1)
      • Power Toys (1)
    • NodeJS (4)
      • nvm (1)
      • React (1)
      • Vue (1)
    • Dev Language (3)
      • Java (2)
      • Kotlin (1)
    • Spring Boot (17)
      • Gradle (1)
      • JPA (3)
    • DB (4)
      • MariaDB (3)
      • Redis (0)
    • Android (6)
      • Debug (3)
    • Nginx (3)
      • Debug (1)
    • Intellij (0)
    • Network (1)
    • Git (2)
      • GitHub (2)
    • Chrome Extension (0)
    • ETC (5)
      • Monitoring (2)
    • Linux (1)
      • WSL (1)
    • Visual Studio (1)
    • Side Project (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Android Studio
  • 알고리즘
  • 안드로이드 스튜디오
  • 프로그래머스
  • docker
  • 티스토리챌린지
  • JPA
  • java
  • spring boot
  • 레벨3
  • nginx
  • 백준
  • 고득점KIT
  • 고득점 Kit
  • 레벨2
  • 오블완
  • DB
  • 연습문제
  • mariadb
  • kotlin

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
sggnology

하늘속에서IT

Android :: Notification을 사용하여 간단한 알림을 만들기(예제포함)
Android

Android :: Notification을 사용하여 간단한 알림을 만들기(예제포함)

2021. 5. 17. 00:12
728x90

안드로이드의 Notification을 구현하려면, Notification Channel을 생성해야 합니다.(특정 조건에서만 구현)

Android 버전 `O` 이상부터, Notification Channel 개념이 추가되었습니다.
따라서, `O`버전 이상에 대해서 Channel을 추가해 주어야 합니다.

 

1. activity_main.xml 수정

  • 이번 에제에서는 버튼 클릭으로 동작되는 Notification을 살펴볼 것입니다.
<?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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_alert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="292dp"
        android:text="Notification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

2. Notification 생성

  • Intent 는 PendingIntent내에서 필요하기 때문이다.
  • PendingIntent는 Notification.setContentIntent(...) 의 인수로 들어가게된다.(클릭시의 동작을 위해)
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
        this,
        0,
        notificationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setContentTitle("TITLE")
        .setContentText("TEXT")
        .setSmallIcon(R.drawable.ic_baseline_4k_24)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Notificaiton의 우선순위
        .setContentIntent(pendingIntent) // Noti.. 가 클릭되었을때의 동작
        .setWhen(System.currentTimeMillis()) // Timestamp 표시를 위해
        .setAutoCancel(true);
        
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

 

3. Notification Channel 생성(오레오 버전 `O` 이상)

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
  NotificationChannel channel = new NotificationChannel(
    NOTIFICATION_CHANNEL_ID,
    channelName,
    importance
  );
  channel.setDescription(description);

  assert notificationManager != null; // notificaitonManager의 객체 생성이 되지 않았다면 코드 실행이 되지 않습니다.
  notificationManager.createNotificationChannel(channel);
}

 

4. MainActivity.java

public class MainActivity extends AppCompatActivity {

    public static final String NOTIFICATION_CHANNEL_ID = "1001";
    private CharSequence channelName = "노티피케이션 채널";
    private String description = "해당 채널에 대한 설명";
    private int importance = NotificationManager.IMPORTANCE_HIGH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_alert = findViewById(R.id.btn_alert);
        btn_alert.setOnClickListener(v->{

            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    this,
                    0,
                    notificationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setContentTitle("TITLE")
                    .setContentText("TEXT")
                    .setSmallIcon(R.drawable.ic_baseline_add_alert_24)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                CharSequence channelName = "노티피케이션 채널";
                String description = "해당 채널에 대한 설명";
                int importance = NotificationManager.IMPORTANCE_HIGH;

                NotificationChannel channel = new NotificationChannel(
                        NOTIFICATION_CHANNEL_ID,
                        channelName,
                        importance
                );
                channel.setDescription(description);

                assert notificationManager != null;
                notificationManager.createNotificationChannel(channel);
            }

            notificationManager.notify(1234, builder.build());
        });
    }
}

 

버튼 누를시 Notification

 

알림창 화면

 

5. 참고 블로그

https://webnautes.tistory.com/665

728x90

'Android' 카테고리의 다른 글

Android :: RoomDatabase inital data(PrePopulating) 데이터베이스 초기 데이터 값 저장하기  (0) 2021.05.20
Android :: Toolbar 사용 방법과 메뉴 커스터마이징(three dots image color, 메뉴의 위치, 예제포함)  (0) 2021.05.11
    'Android' 카테고리의 다른 글
    • Android :: RoomDatabase inital data(PrePopulating) 데이터베이스 초기 데이터 값 저장하기
    • Android :: Toolbar 사용 방법과 메뉴 커스터마이징(three dots image color, 메뉴의 위치, 예제포함)
    sggnology
    sggnology
    하늘은 파란색이니까 내 삶도 파란색이길 ㅎㅎ

    티스토리툴바