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

안드로이드에서 벨소리·알람·알림 사운드를 재생하는 방법

개요

이 튜토리얼에서는 안드로이드 앱에서 벨소리(ringtone), 알람(alarm), 알림(notification) 사운드를 재생하는 방법을 단계별로 살펴봅니다. 핵심 원리는 RingtoneManager를 사용해 시스템 기본 사운드의 URI를 가져온 뒤, MediaPlayer로 해당 사운드를 재생하는 것입니다. 아래 가이드를 따라 직접 구현해 보세요.

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단계 — MainActivity 작성 (MainActivity.java)

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

package app.tutorialspoint.com.notifyme;

import android.app.NotificationManager;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
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 {
   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 alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            MediaPlayer mp = MediaPlayer.create(getApplicationContext(), alarmSound);
            mp.start();
            NotificationCompat.Builder mBuilder =
               new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                  .setSmallIcon(R.drawable.ic_launcher_foreground)
                  .setContentTitle("Test")
                  .setContentText("Hello! This is my first push notification");
            NotificationManager mNotificationManager = (NotificationManager)
               getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify((int) System.currentTimeMillis(),
               mBuilder.build());
         }
      });
   }
}

코드 설명: 버튼을 클릭하면 RingtoneManager.getDefaultUri()TYPE_NOTIFICATION을 전달하여 기본 알림음의 URI를 가져옵니다. 이후 MediaPlayer.create()로 플레이어 인스턴스를 생성하고 start() 메서드를 호출해 사운드를 재생합니다. 이어서 NotificationCompat.Builder로 제목과 내용을 담은 알림을 구성한 뒤, NotificationManagernotify() 메서드를 호출하여 실제 알림을 화면에 표시합니다.

4단계 — 매니페스트 설정 (AndroidManifest.xml)

androidManifest.xml 파일에 다음 코드를 추가합니다. 진동 사용을 위한 VIBRATE 권한을 선언하고, Firebase 메시징 이벤트를 처리할 MyFirebaseMessagingService를 등록합니다.

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

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 대상 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 나타납니다. 버튼을 누르면 기본 알림음이 재생되면서 동시에 푸시 알림이 표시되는 것을 확인할 수 있습니다.

안드로이드에서 벨소리·알람·알림 사운드를 재생하는 방법