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

안드로이드 알림에서 작은 아이콘 대신 큰 아이콘(Large Icon)을 설정하는 방법

개요

이 튜토리얼에서는 안드로이드 알림(Notification)에서 작은 아이콘(small icon) 대신 큰 아이콘(large icon)을 설정하는 방법을 단계별로 살펴봅니다. 일반적으로 상태바에는 작은 아이콘이 표시되지만, setLargeIcon() 메서드를 활용하면 알림 펼침 화면에 더 크고 시각적인 아이콘을 함께 보여줄 수 있습니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 뒤, 새 프로젝트를 만들기 위해 필요한 모든 세부 정보를 입력합니다.

2단계 — 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: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>

화면 중앙에 버튼 하나를 배치하는 간단한 레이아웃입니다. 이 버튼을 클릭하면 알림이 생성됩니다.

3단계 — MainActivity.java 코드 추가

다음 코드를 src/MainActivity.java 파일에 추가합니다.

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.BitmapFactory;
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("Notification Title");
        mBuilder.setContentText("Content to be added");
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
        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());
    }
}

핵심 포인트

큰 아이콘 설정의 핵심은 다음 코드입니다. 비트맵 형태의 이미지를 디코딩하여 알림 빌더에 전달합니다.

mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));

또한 안드로이드 8.0(오레오, API 26) 이상에서는 반드시 NotificationChannel을 생성해야 알림이 정상적으로 표시됩니다. 위 코드는 OS 버전을 확인한 후 채널을 동적으로 생성하도록 처리하고 있습니다.

4단계 — AndroidManifest.xml 코드 추가

다음 코드를 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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 기본 화면이 표시됩니다.

화면 중앙의 create notification 버튼을 누르면 알림이 생성되며, 알림을 펼쳤을 때 설정한 큰 아이콘이 함께 표시되는 것을 확인할 수 있습니다.