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

안드로이드 알림(Notification) 아이콘 설정하는 방법 – 단계별 완벽 가이드

개요

이 예제는 Android 앱에서 알림(Notification) 아이콘을 설정하는 방법을 단계별로 설명합니다. 버튼을 클릭하면 지정한 아이콘이 포함된 푸시 알림이 생성되는 간단한 데모 앱을 만들어 보겠습니다.

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 파일에 다음 코드를 추가합니다. 핵심은 NotificationCompat.BuildersetSmallIcon() 메서드입니다. 이 메서드에 전달되는 드로어블 리소스가 바로 알림에 표시될 아이콘입니다.

package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Objects;
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) {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this,
               default_notification_channel_id )
               .setSmallIcon(R.drawable. ic_launcher_foreground )
               .setContentTitle( "Test" )
               .setContentText( "Hello! This is my first push notification" ) ;
            NotificationManager mNotificationManager = (NotificationManager)
               getSystemService(Context. NOTIFICATION_SERVICE ) ;
            mNotificationManager.notify( 1 , mBuilder.build()) ;
         }
      });
   }
}

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" >
   <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(실행) 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면 앱이 설치·실행되고, 아래와 같은 기본 화면이 표시됩니다.

안드로이드 알림(Notification) 아이콘 설정하는 방법 – 단계별 완벽 가이드

화면의 Create notification 버튼을 누르면 상태바에 알림 아이콘이 나타나고, 알림창을 아래로 당기면 'Test'라는 제목과 함께 첫 번째 푸시 알림을 확인할 수 있습니다.

추가 팁: 알림 아이콘 설정 시 주의사항

  • setSmallIcon()은 필수입니다. 이 값을 설정하지 않으면 Android 8.0(API 26) 이상에서 알림이 정상적으로 표시되지 않습니다.
  • 흰색 + 투명 배경의 아이콘을 사용하세요. 상태바용 스몰 아이콘은 컬러 이미지가 아니라 흰색 실루엣 형태로 제작해야 기기마다 올바르게 렌더링됩니다.
  • 알림 채널(Channel)을 활용하세요. Android 8.0부터는 채널 ID를 반드시 지정해야 하며, 채널별로 소리·진동 등의 동작을 다르게 설정할 수 있습니다.
  • 큰 아이콘은 setLargeIcon()으로 추가할 수 있으며, 알림창 펼침 영역에 앱 로고나 사용자 프로필 이미지 등을 표시할 때 유용합니다.

지금까지 Android에서 알림 아이콘을 설정하고 푸시 알림을 발생시키는 전체 과정을 살펴보았습니다. 위 코드를 응용하면 다양한 스타일의 알림을 손쉽게 구현할 수 있습니다.