이 튜토리얼에서는 안드로이드 앱에서 벨소리(Ringtone), 알람(Alarm), 알림(Notification) 사운드를 재생하는 방법을 단계별로 살펴봅니다. RingtoneManager로 기본 알림음의 URI를 가져오고, MediaPlayer로 실제 소리를 재생한 뒤, 함께 알림(Notification)까지 발송하는 예제입니다.
1단계 — 새 프로젝트 만들기
Android Studio에서 File ⇒ New Project 메뉴로 이동한 뒤, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 작성 (res/layout/activity_main.xml)
아래 코드를 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단계 — 메인 액티비티 구현 (src/MainActivity.java)
다음으로 MainActivity.java에 아래 코드를 추가합니다. 버튼을 클릭하면 RingtoneManager.getDefaultUri()로 시스템 기본 알림음 URI를 가져오고, MediaPlayer로 즉시 재생한 후 알림을 생성합니다.
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.TYPE_NOTIFICATION: 기본 알림음 URI를 가져옵니다.TYPE_ALARM(알람) 또는TYPE_RINGTONE(벨소리)로 변경하면 다른 종류의 시스템 사운드도 재생할 수 있습니다.MediaPlayer.create(): URI를 바탕으로 미디어 플레이어 인스턴스를 생성하고 곧바로 재생 준비를 마칩니다.mNotificationManager.notify(): 고유 ID로 알림을 발송합니다. 여기서는 현재 시간을 ID로 사용해 매번 새로운 알림이 표시되도록 했습니다.
4단계 — 매니페스트 설정 (androidManifest.xml)
마지막으로 AndroidManifest.xml에 아래 코드를 추가합니다. 진동 권한과 FCM(Firebase Cloud Messaging) 서비스 선언이 포함되어 있습니다.
<?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 ▶ 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시된 앱이 기기에서 실행됩니다.
버튼을 누르면 시스템 기본 알림음이 재생되면서 동시에 "Hello! This is my first push notification" 내용의 알림이 상단에 나타나는 것을 확인할 수 있습니다.
