Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 잠금 화면에는 알림을 숨기고 알림 영역에만 표시하는 방법

이 튜토리얼에서는 잠금 화면(락 스크린)에는 알림을 표시하지 않으면서, 알림 영역(알림 센터)에는 정상적으로 유지되도록 안드로이드 알림을 구현하는 방법을 단계별로 살펴보겠습니다.

핵심은 NotificationCompat.BuildersetVisibility() 메서드입니다. 이 메서드에 VISIBILITY_SECRET 값을 전달하면 해당 알림은 잠금 화면에서 완전히 숨겨지지만, 기기 잠금을 해제한 후 알림 영역에서는 계속 확인할 수 있습니다.

Step 1 — 새 프로젝트 생성

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

Step 2 — res/layout/activity_main.xml 작성

메인 레이아웃 파일에 아래 코드를 추가합니다. 화면 중앙에 'Create notification' 버튼 하나를 배치하는 간단한 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:onClick="createNotification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="Create notification" />

</RelativeLayout>

Step 3 — res/layout/custom_notification_layout.xml 작성

커스텀 알림 레이아웃 파일을 새로 생성하고 아래 코드를 추가합니다. 이 레이아웃은 앱 아이콘, 제목 텍스트, 입력 필드를 포함한 커스텀 뷰(RemoteViews)로 사용됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="96dp"
    android:padding="10dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentStart="true"
        android:layout_marginEnd="10dp"
        android:contentDescription="@string/app_name"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/image"
        android:text="Testing"
        android:textColor="#000"
        android:textSize="18sp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginTop="8dp"
        android:layout_toEndOf="@+id/image"
        android:hint="Enter something..."
        android:inputType="text"
        android:textSize="14sp" />

</RelativeLayout>

Step 4 — src/MainActivity.java 작성

메인 액티비티에 아래 코드를 추가합니다. 여기서 가장 중요한 부분은 mBuilder.setVisibility(NotificationCompat.VISIBILITY_SECRET) 라인으로, 이 설정 덕분에 알림이 잠금 화면에 나타나지 않습니다.

package app.tutorialspoint.com.notifyme;

import android.app.KeyguardManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RemoteViews;

public class MainActivity extends AppCompatActivity {

    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

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

    public void createNotification(View view) {
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
        mBuilder.setContent(contentView);
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);

        // 잠금 화면에서 알림을 완전히 숨김
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_SECRET);

        // 기기가 잠겨 있을 경우 우선순위를 최소로 설정
        KeyguardManager keyguardManager = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        if (keyguardManager.isKeyguardLocked())
            mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);

        // Android 8.0(Oreo) 이상에서는 알림 채널 생성 필수
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

주요 코드 설명

  • setVisibility(NotificationCompat.VISIBILITY_SECRET): 알림 공개 수준을 '비밀'로 지정하여 잠금 화면에서 해당 알림을 완전히 숨깁니다. 다른 옵션으로는 VISIBILITY_PUBLIC(잠금 화면에 전체 표시)과 VISIBILITY_PRIVATE(잠금 화면에는 기본 정보만 표시)가 있습니다.
  • PRIORITY_MIN: KeyguardManager로 기기 잠금 여부를 확인한 후, 잠겨 있다면 알림 우선순위를 최소로 낮춰 헤드업 팝업 등의 노출도 최소화합니다.
  • NotificationChannel: Android 8.0(API 26) 이상에서는 반드시 알림 채널을 생성해야 하므로 SDK 버전을 체크한 뒤 채널을 등록합니다.

Step 5 — AndroidManifest.xml 수정

매니페스트 파일에 아래와 같이 진동 권한과 액티비티 설정을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행할 기기 목록에서 본인의 모바일 기기를 선택하면, 앱이 설치되어 실행됩니다.

앱이 실행되면 화면 중앙의 'Create notification' 버튼을 눌러 알림을 생성해 보세요. 그런 다음 기기를 잠그면 잠금 화면에는 해당 알림이 표시되지 않습니다. 하지만 기기 잠금을 해제하고 상단을 아래로 당겨 알림 영역을 열면, 커스텀 레이아웃이 적용된 알림이 그대로 남아 있는 것을 확인할 수 있습니다.

안드로이드 잠금 화면에는 알림을 숨기고 알림 영역에만 표시하는 방법

마무리

이처럼 setVisibility() 메서드를 활용하면 민감한 개인정보가 담긴 알림(예: 메시지 내용, OTP 번호 등)이 잠금 화면에 노출되는 것을 방지하면서도, 사용자가 기기를 잠금 해제했을 때는 정상적으로 알림을 확인할 수 있게 만들 수 있습니다. 보안이 중요한 앱이라면 꼭 적용해 볼 만한 기능입니다.