안드로이드 자바

[Java][Android] 화면이 꺼졌을때 Notification 보기

teamnova 2023. 5. 13. 12:00
728x90

안녕하세요.

이번에는 안드로이드 기기의 화면이 꺼진 상태에서 Notification이 왔을때 화면을 잠시 켜고 Notification을 표시하는 예제를 진행하겠습니다.

 

PowerManager 클래스의 메서드인 WakeLock을 사용하면 화면을 켤 수 있습니다.

사용하기 위해 Manifest에 권한을 추가해줍니다.

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

 

레이아웃 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"
    tools:context=".MainActivity">


    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="3초 뒤에 Notification 띄우기"
        android:textSize="20dp"
        android:padding="20dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.java 를 다음과 같이 만듭니다.

package com.example.notificationpractice_1;

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.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    PowerManager powerManager;
    PowerManager.WakeLock wakeLock;

    Button btn_notification;

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

        btn_notification = (Button) findViewById(R.id.btn_notification);

        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

        wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "WAKELOCK");

        btn_notification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 알림 표시하고 화면 켠 후, 화면이 다시 꺼지게 해준다.
                try {
                    Thread.sleep(3000); // 3초 기다렸다가

                    notifyDetection(); // Notification 띄우기
                    wakeLock.acquire(); // WakeLock 깨우기

                    Thread.sleep(3000); // 3초 기다렸다가

                    wakeLock.release(); // WakeLock 해제. 화면이 다시 꺼지게 해준다.

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        });
    }

    public void notifyDetection() {

        int icon = R.drawable.ic_launcher_foreground;
        String title = "알림 제목";
        String description = "알림 내용입니다.";

        String CHANNEL_ID = "NotificationChannelID";


        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0 /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "notification_name";

            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .setContentTitle(title)
                .setContentText(description)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setDefaults(NotificationCompat.DEFAULT_VIBRATE)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setAutoCancel(true);

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

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

    }
}

 

 

결과는 다음과 같습니다.