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

Android에서 긴 텍스트 알림(Notification) 만드는 방법 – BigTextStyle 활용 가이드

Android에서 기본 알림(Notification)은 텍스트가 길어질 경우 한 줄로 잘려서 전체 내용을 확인할 수 없습니다. 이럴 때 BigTextStyle을 사용하면 알림을 펼쳤을 때 긴 텍스트 전체를 표시할 수 있습니다. 이번 튜토리얼에서는 버튼 하나를 누르면 긴 텍스트가 포함된 알림이 생성되는 간단한 예제 앱을 만들어 보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 새 프로젝트를 만들기 위해 필요한 모든 정보를 입력합니다.

2단계: 레이아웃 파일 작성 (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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:onClick="createNotification"
        android:text="create notification" />

</RelativeLayout>

버튼의 android:onClick="createNotification" 속성 덕분에 별도의 클릭 리스너 없이도 버튼을 누르면 MainActivity의 createNotification() 메서드가 자동으로 호출됩니다.

3단계: MainActivity 작성 (src/MainActivity.java)

핵심 로직입니다. NotificationCompat.BigTextStyle을 사용해 긴 텍스트를 처리하는 부분을 주목하세요.

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
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";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    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(getResources().getString(R.string.lorem_ipsum));

        // BigTextStyle을 적용하면 알림을 펼쳤을 때 긴 텍스트 전체가 표시됩니다.
        mBuilder.setStyle(new NotificationCompat.BigTextStyle()
                .bigText(getResources().getString(R.string.lorem_ipsum)));

        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);

        // Android 8.0(Oreo) 이상에서는 알림 채널 생성이 필수입니다.
        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());
    }
}

주요 포인트 정리

  • setContentText(): 접힌 상태에서 표시되는 기본 텍스트를 설정합니다.
  • setStyle(BigTextStyle().bigText(...)): 알림을 아래로 펼치면 긴 텍스트 전체가 여러 줄로 표시됩니다.
  • setAutoCancel(true): 사용자가 알림을 탭하면 자동으로 사라집니다.
  • 알림 채널: Android 8.0(API 26)부터는 채널을 생성하지 않으면 알림이 표시되지 않으므로 반드시 처리해야 합니다.

4단계: 매니페스트 설정 (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>

    </application>
</manifest>

앱 실행 및 결과 확인

이제 앱을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면 앱이 설치되고 실행됩니다.

앱이 실행되면 화면 중앙의 create notification 버튼을 탭해 보세요. 알림이 생성되고, 해당 알림을 아래로 드래그하여 펼치면 lorem_ipsum 문자열 리소스에 담긴 긴 텍스트 전체가 여러 줄로 표시되는 것을 확인할 수 있습니다.

이처럼 BigTextStyle을 활용하면 짧은 요약만 보여주는 기본 알림과 달리, 이메일 본문이나 뉴스 요약처럼 긴 내용을 알림에서 바로 확인할 수 있어 사용자 경험을 크게 향상시킬 수 있습니다.