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

안드로이드에서 여러 개의 알림을 동시에 표시하는 방법


이 튜토리얼에서는 안드로이드 앱에서 여러 개의 알림을 동시에 표시하는 방법을 단계별로 알아봅니다. 버튼을 클릭할 때마다 새로운 알림이 생성되어 알림 창에 계속 쌓이도록 구현하는 것이 목표입니다.

핵심 원리: 고유한 알림 ID

여러 알림이 동시에 표시되는 비결은 NotificationManager.notify() 메서드의 첫 번째 인자인 알림 ID(notification ID)에 있습니다. 같은 ID로 notify()를 호출하면 기존 알림이 업데이트(덮어쓰기)되지만, 이 예제에서는 (int) System.currentTimeMillis()를 사용해 호출 시점마다 고유한 ID를 부여합니다. 그 결과 기존 알림을 대체하지 않고 새로운 알림이 계속 추가됩니다.

1단계 — 새 프로젝트 만들기

Android Studio에서 File → New Project를 선택한 뒤 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계 — 레이아웃 작성(activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 한가운데에 'Create notification' 버튼 하나를 배치하는 단순한 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Create notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

3단계 — 알림음 파일 추가

알림음으로 사용할 오디오 파일(예: quite_impressed.mp3)을 res/raw 폴더에 넣습니다. raw 폴더가 없다면 res 폴더를 마우스 오른쪽 버튼으로 클릭한 후 New → Android Resource Directory에서 리소스 타입을 'raw'로 지정해 생성하면 됩니다.

안드로이드에서 여러 개의 알림을 동시에 표시하는 방법

4단계 — MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. 버튼 클릭 시 알림을 생성하며, 안드로이드 8.0(오레오, API 26) 이상에서는 반드시 알림 채널(NotificationChannel)을 먼저 생성해야 한다는 점에 유의하세요. 이 채널에는 LED 알림 색상, 진동 패턴, 사용자 지정 사운드가 함께 설정됩니다.

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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);
        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/quite_impressed.mp3");
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("Test")
                        .setSound(sound)
                        .setContentText("Hello! This is my first push notification");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_ALARM)
                            .build();
                    int importance = NotificationManager.IMPORTANCE_HIGH;
                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
                    notificationChannel.enableLights(true);
                    notificationChannel.setLightColor(Color.RED);
                    notificationChannel.enableVibration(true);
                    notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                    notificationChannel.setSound(sound, audioAttributes);
                    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                    assert mNotificationManager != null;
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
                assert mNotificationManager != null;
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            }
        });
    }
}

5단계 — AndroidManifest.xml 확인

AndroidManifest.xml에 MainActivity가 아래와 같이 정상적으로 등록되어 있는지 확인합니다.

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

    <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>

앱 실행 및 결과 확인

실제 안드로이드 기기를 컴퓨터에 연결한 상태에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭해 앱을 실행합니다. 배포 대상으로 자신의 모바일 기기를 선택하면 해당 기기에 앱이 설치·실행됩니다.

'Create notification' 버튼을 여러 번 눌러 보세요. 클릭할 때마다 서로 다른 ID를 가진 알림이 생성되어 상태 표시줄과 알림 창에 여러 개의 알림이 동시에 표시되는 것을 확인할 수 있습니다.

안드로이드에서 여러 개의 알림을 동시에 표시하는 방법

참고: 안드로이드 13(API 33) 이상에서는 알림 권한(android.permission.POST_NOTIFICATIONS)이 런타임 권한으로 요구됩니다. 매니페스트에 권한을 선언하고 사용자에게 허용을 요청해야 알림이 정상적으로 표시됩니다.