개요
이 튜토리얼에서는 안드로이드 앱에서 알림(Notification)을 생성할 때 진동(Vibrate)과 알림 소리(Sound)를 함께 설정하는 방법을 단계별로 알아봅니다. 사용자가 앱을 열어보지 않고도 새로운 소식을 즉시 인지할 수 있도록 하는 핵심 기능입니다.
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.java 작성
다음 코드를 src/MainActivity.java 파일에 추가합니다. 여기서 핵심은 setVibrate()와 setSound() 메서드입니다.
- setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}): 진동 패턴을 지정합니다. 배열의 값은 밀리초(ms) 단위로, [대기 시간, 진동 시간, 대기 시간, 진동 시간...] 순서로 해석됩니다.
- setSound(alarmSound):
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)으로 기본 알림음의 URI를 가져와 설정합니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.content.Context;
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);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this,
default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setContentTitle("Test")
.setSound(alarmSound)
.setContentText("Hello! This is my first push notification");
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
});
}
}버튼을 클릭하면 알림 빌더(Builder)를 통해 제목, 내용, 아이콘, 진동 패턴, 알림음이 포함된 알림이 생성되고, NotificationManager.notify()를 호출하여 실제로 기기에 표시됩니다.
4단계: AndroidManifest.xml 권한 설정
진동 기능을 사용하려면 반드시 VIBRATE 권한을 선언해야 합니다. 다음 코드를 androidManifest.xml에 추가합니다.
<?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 ▶ 아이콘을 클릭합니다. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

화면의 'Create notification' 버튼을 누르면, 설정된 진동 패턴과 함께 기본 알림음이 재생되며 알림이 나타나는 것을 확인할 수 있습니다.
참고 사항
안드로이드 8.0(API 26) 이상에서는 알림 채널(Notification Channel)을 생성할 때 setVibrationPattern()과 setSound()를 채널 설정에 적용해야 진동과 소리가 정상적으로 동작합니다. 위 예제처럼 Builder에서 직접 설정하는 방식은 하위 호환성을 위해 유용하지만, 최신 버전을 타겟팅한다면 채널 설정을 함께 고려하는 것이 좋습니다.