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

안드로이드 알림(Notification) 완벽 가이드: 진동, 소리, 액션 버튼, 빅 뷰 스타일 구현 예제

이 튜토리얼에서는 진동(Vibration), 소리(Sound), 액션 버튼(Action), 그리고 빅 뷰 스타일(Big View Styles)을 모두 포함한 안드로이드 알림(Notification)을 구현하는 방법을 단계별로 알아봅니다.

안드로이드에서 알림은 사용자에게 중요한 정보를 전달하는 핵심 기능입니다. 이 예제를 따라 하면 확장 가능한 빅 텍스트 스타일의 알림과 사용자가 바로 상호작용할 수 있는 액션 버튼까지 갖춘 알림을 만들 수 있습니다.

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단계: 메인 액티비티 구현

src/MainActivity.java 파일에 아래 코드를 추가합니다. 이 코드가 이 예제의 핵심으로, 다음과 같은 요소들을 포함합니다.

  • PendingIntent: 알림을 탭하거나 액션 버튼을 눌렀을 때 MainActivity를 실행하도록 연결합니다.
  • addAction(): 알림에 'Add' 액션 버튼을 추가합니다.
  • BigTextStyle: 알림이 확장되었을 때 긴 텍스트를 표시할 수 있는 빅 뷰 스타일을 적용합니다.
  • NotificationManager: 시스템 알림 서비스를 통해 실제 알림을 발송합니다.
package app.tutorialspoint.com.notifyme;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                final PendingIntent resultPendingIntent =
                        PendingIntent.getActivity(
                                MainActivity.this,
                                0,
                                intent,
                                PendingIntent.FLAG_CANCEL_CURRENT
                        );
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this,
                                default_notification_channel_id)
                                .setSmallIcon(R.drawable.ic_launcher_foreground)
                                .setContentTitle("Test")
                                .addAction(R.drawable.ic_launcher_foreground, "Add", resultPendingIntent)
                                .setContentIntent(resultPendingIntent)
                                .setStyle(new NotificationCompat.BigTextStyle().bigText("Big View Styles"))
                                .setContentText("Hello! This is my first push notification");
                NotificationManager mNotificationManager = (NotificationManager)
                        getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            }
        });
    }
}

4단계: 매니페스트 설정

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>

        <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 버튼을 누르면 제목, 본문 텍스트, 'Add' 액션 버튼이 포함된 알림이 생성됩니다. 알림을 아래로 당겨 확장하면 BigTextStyle이 적용된 빅 뷰 형태로 내용이 표시되는 것을 확인할 수 있습니다.

안드로이드 알림(Notification) 완벽 가이드: 진동, 소리, 액션 버튼, 빅 뷰 스타일 구현 예제

마무리 및 참고 사항

이 예제는 안드로이드 8.0(API 26) 이상에서 필수인 알림 채널(Notification Channel) 개념도 함께 다룹니다. 채널 ID를 Builder에 지정하지 않으면 오레오 이상 기기에서 알림이 표시되지 않으므로, 실제 프로젝트에서는 NotificationChannel 객체를 생성하고 createNotificationChannel()로 등록하는 과정을 반드시 거쳐야 합니다.

또한 진동 패턴이나 소리를 세부적으로 제어하고 싶다면 채널 생성 시 enableVibration(true), setSound() 등의 메서드를 활용하면 됩니다. 이렇게 완성된 알림 시스템은 FCM(Firebase Cloud Messaging)과 연동하여 원격 푸시 알림으로도 손쉽게 확장할 수 있습니다.