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

[JAVA][Android] 안드로이드 - 알림 만들기 및 알림 탭하여 액티비티로 이동

by teamnova 2021. 10. 21.

알림은 사용 중이 아닌 앱의 이벤트에 관한 짧고 시기적절한 정보를 제공하는 기능입니다.

 

이번 게시글에서는 버튼을 클릭했을 때 알림이 생성되고, 알림을 탭하면 원하는 액티비티로 이동하는 기능을 구현해 보겠습니다.

 

먼저 기본 알림을 만드는 법부터 알아보겠습니다.

가장 기본적이고 간단한 형태(축소된 형태라고도 함)의 알림에는 아이콘, 제목 및 소량의 콘텐츠 텍스트가 표시됩니다.

예시) 제목과 텍스트가 있는 알림

 

알림 콘텐츠 설정

 

시작하려면 NotificationCompat.Builder 객체를 사용하여 알림 콘텐츠를 생성해야 합니다.

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle(textTitle)
            .setContentText(textContent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

 

  • setSmallIcon()으로 설정한 작은 아이콘. 사용자가 볼 수 있는 유일한 필수 콘텐츠입니다.
  • setContentTitle()로 설정한 제목
  • setContentText()로 설정한 본문 텍스트
  • setPriority()로 설정한 알림 우선순위. 우선순위에 따라 Android 7.1 이하에서 알림이 얼마나 강제적이어야 하는지가 결정됩니다. (Android 8.0 이상의 경우 다음 섹션에 표시된 채널 중요도를 대신 설정해야 합니다.)

 

알림의 탭 작업 설정

모든 알림은 일반적으로 앱에서 알림에 상응하는 활동을 열려면 탭에 응답해야 합니다. 이 작업을 하려면 PendingIntent 객체로 정의된 콘텐츠 인텐트를 지정하여 setContentIntent()에 전달해야 합니다.

 

    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)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

 

알림 표시

알림을 표시하려면 NotificationManagerCompat.notify()를 호출하여 알림의 고유 ID와 NotificationCompat.Builder.build() 의 결과를 전달합니다.

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    notificationManager.notify(notificationId, builder.build());

 

전체 코드

 

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:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/create"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="알림 생성"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private Button create; // 알림생성버튼

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

        create = findViewById(R.id.create);

        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createNotification("DEFAULT",1,"title","text");
            }
        });
    }

    void createNotification(String channelId, int id, String title, String text){
        Intent intent = new Intent(this,SubActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle(title)
                .setContentText(text)
                // Set the intent that will fire when the user taps the notification
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

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

https://stickode.com/detail.html?no=2545

 

스틱코드

 

stickode.com

createNotification 메서드를 스틱코드에서 불러와서 사용합니다.