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

Android Oreo(오레오) 이상 버전에서 사용자 지정 알림 사운드 설정하기

이 튜토리얼에서는 Android 8.0 Oreo(오레오) 및 그 이상 버전에서 알림(Notification)에 사용자 지정 사운드를 적용하는 방법을 단계별로 살펴봅니다.

핵심 포인트: Android 8.0부터는 알림의 세부 동작(사운드, 진동, LED 등)이 NotificationChannel(알림 채널)이 관리합니다. 따라서 빌더의 setSound()만으로는 오레오 이상 기기에서 사운드가 재생되지 않으며, 반드시 채널에 AudioAttributes와 함께 사운드를 지정해야 합니다. 또한 채널은 한 번 생성되면 코드로 수정할 수 없으므로, 설정을 변경하려면 앱을 재설치하거나 새로운 채널 ID를 사용해야 합니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

2단계 — 레이아웃 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?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단계 — raw 폴더에 사운드 파일 추가

재생할 오디오 파일(예: quite_impressed.mp3)을 res/raw 폴더에 넣습니다. raw 폴더가 없다면 res 디렉터리를 마우스 오른쪽 버튼으로 클릭한 후 New ⇒ Directory 메뉴로 새로 생성할 수 있습니다.

Android Oreo(오레오) 이상 버전에서 사용자 지정 알림 사운드 설정하기

4단계 — MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다.

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) {
                // raw 폴더의 사운드 파일에 대한 리소스 Uri 생성
                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);

                // Android 8.0(Oreo) 이상인 경우 알림 채널 생성
                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 파일에 다음 코드를 추가합니다.

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

동작 원리 요약

  • 리소스 Uri 생성: ContentResolver.SCHEME_ANDROID_RESOURCE를 이용해 raw 폴더 내 mp3 파일을 가리키는 Uri를 만듭니다.
  • 오레오 미만 기기: 빌더의 setSound()에 지정된 사운드가 그대로 적용됩니다.
  • 오레오 이상 기기: IMPORTANCE_HIGH 중요도로 알림 채널을 생성하고, setSound()에 사운드 Uri와 함께 USAGE_ALARM 속성을 전달해야 사운드가 재생됩니다.
  • 부가 효과: LED 색상, 진동 패턴 등도 채널 단위로 함께 설정할 수 있습니다.

실행 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 여기서는 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기의 기본 화면에 다음과 같은 결과가 표시됩니다.

Android Oreo(오레오) 이상 버전에서 사용자 지정 알림 사운드 설정하기