이 튜토리얼에서는 Android 앱에서 알림(Notification)을 수신할 때 사용자가 직접 선택한 사용자 지정 사운드를 재생하는 방법을 단계별로 살펴봅니다.
핵심 아이디어는 RingtoneManager의 알림음 선택기를 통해 사용자가 원하는 사운드를 고르게 하고, 그 결과 URI를 저장한 뒤 알림 채널에 적용하는 것입니다. 그럼 바로 시작해 보겠습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 작성 (res/layout/activity_main.xml)
다음 코드를 res/layout/activity_main.xml 파일에 추가합니다. 이 레이아웃에는 '알림음 설정' 버튼과 '알림 생성' 버튼 두 개가 배치됩니다.
<?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="setRingtone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="set ringtone" />
<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>3단계 — 메인 액티비티 작성 (src/MainActivity.java)
다음 코드를 MainActivity.java에 추가합니다. 이 클래스에서는 다음과 같은 작업이 이루어집니다.
setRingtone():RingtoneManager.ACTION_RINGTONE_PICKER인텐트를 실행해 사용자가 알림음을 선택할 수 있는 시스템 다이얼로그를 엽니다.onActivityResult(): 사용자가 선택한 알림음의 URI를 받아chosenRingtone변수에 저장합니다.createNotification(): Android 8.0(Oreo) 이상에서는NotificationChannel을 생성하고, 알림을 빌드하여 발송합니다.
package app.tutorialspoint.com.notifyme;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
String chosenRingtone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onNewIntent(getIntent());
}
public void setRingtone(View view) {
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
this.startActivityForResult(intent, 5);
}
public void createNotification(View view) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("Notify Me");
mBuilder.setContentText("Something important!");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
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());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 5) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null) {
this.chosenRingtone = uri.toString();
} else {
this.chosenRingtone = null;
}
}
}
}참고 사항
Android 8.0(API 26)부터는 알림 사운드가 개별 알림이 아닌 알림 채널(NotificationChannel) 단위로 관리됩니다. 따라서 실제 서비스에서는 사용자가 선택한 사운드 URI를 notificationChannel.setSound(uri, audioAttributes) 형태로 채널에 적용하면 됩니다. 채널은 한 번 생성되면 사운드 설정을 변경할 수 없으므로, 사운드 변경 시에는 새로운 채널 ID로 채널을 다시 만들어야 합니다.
4단계 — 매니페스트 설정 (AndroidManifest.xml)
다음 코드를 AndroidManifest.xml에 추가합니다. 진동 권한(VIBRATE)을 선언하고 메인 액티비티를 등록합니다.
<?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 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run ▶ 아이콘을 클릭하세요. 실행 기기 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 표시됩니다.
앱이 실행되면 다음 순서로 테스트할 수 있습니다.
- 'set ringtone' 버튼을 눌러 시스템 알림음 선택 화면을 열고 원하는 사운드를 선택합니다.
- 'Create notification' 버튼을 눌러 알림을 발생시킵니다.
- 기기 상단에 알림이 표시되며, 선택한 알림 채널의 사운드 설정에 따라 알림음이 재생됩니다.
이렇게 하면 Android에서 알림 수신 시 사용자 지정 사운드를 적용하는 기본 흐름을 완성할 수 있습니다.