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

[Android][Java] Notification에 ProgressBar 사용하기

by teamnova 2023. 4. 15.
728x90

 

안녕하세요. Notification 알림창에 ProgressBar를 추가하는 방법에 대해 알아보겠습니다!

 

먼저 알림을 만들기 위한 버튼이 있는 레이아웃을 제작합니다.

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

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        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>

 

다음으로 자바 파일입니다.

NotiActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class NotiActivity extends AppCompatActivity {

    public final String CHANNEL_ID = "my_notification_channel";
    public static final  int NOTIFICATION_ID = 101;

    public static final String TEXT_REPLY = "text_reply";

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

        Button notificationBtn = findViewById(R.id.button);
        notificationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayNotification(v);
            }
        });
    }


    //알림 설정
    public void displayNotification(View v){

        createNotificationChannel();

        //MainActivity 설정
        Intent mainIntent = new Intent(this, MainActivity.class);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent MainPendingIntent = PendingIntent.getActivity(this , 0, mainIntent, PendingIntent.FLAG_ONE_SHOT);


        //알림설정
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        builder.setSmallIcon(R.drawable.ic_get);
        builder.setContentTitle("이미지 다운로드");
        builder.setContentText("다운로드 중 ...");
        builder.setPriority(NotificationManagerCompat.IMPORTANCE_HIGH);
        builder.setAutoCancel(true); //알림 터치시 자동 삭제할 것인지
        builder.setContentIntent(MainPendingIntent);// 알림 눌렀을 때 실행할 작업 인텐트 설정

        final int max_progress = 100; //최대값

        final NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);

        Thread thread = new Thread()
        {
            @Override
            public void run() {

                int count = 0;

                try {
                    while(count <= 100)
                    {
                        count = count+10;
                        sleep(1000);
                        //progress 설정(최대값,현재값,작업진행 표시유무)
                        builder.setProgress(max_progress, count, false);
                        notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());
                    }

                    builder.setContentText("다운로드가 완료되었습니다.");
                    builder.setProgress(0, 0, false); //초기화
                    notificationManagerCompat.notify(NOTIFICATION_ID, builder.build());

                }catch (InterruptedException e){ }

            }
        };

        thread.start();
    }

    //채널 셋팅
    private void createNotificationChannel(){

        //오레오부터는 알림을 채널에 등록해야 한다.

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            CharSequence name = "my_notification_channel";
            String description = "노티피케이션 채널입니다.";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;

            //채널생성
            NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);

            notificationChannel.setDescription(description);

            //알림매니저 생성
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            //알림매니저에 채널등록록
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
}

 

실행화면입니다.

 

 

궁금한 점은 댓글로 남겨주세요.

 감사합니다!