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

안드로이드 NotificationBuilder 예제 – 알림 생성 단계별 가이드


이 튜토리얼에서는 안드로이드에서 NotificationBuilder(NotificationCompat.Builder)를 사용하여 알림을 생성하는 방법을 단계별로 알아봅니다. NotificationCompat.Builder는 지원 라이브러리에서 제공하는 클래스로, 다양한 안드로이드 버전과 호환되는 알림을 손쉽게 만들 수 있도록 도와줍니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 후, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.

2단계 — activity_main.xml 레이아웃 작성

다음 코드를 res/layout/activity_main.xml에 추가합니다. 이 레이아웃은 화면 한가운데에 'create notification' 버튼 하나를 배치합니다.

<? 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 코드 작성

src/MainActivity.java에 아래 코드를 추가합니다. 버튼을 클릭하면 createNotification() 메서드가 호출되어 알림 채널을 생성하고 알림을 화면에 표시합니다.

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 \uD83D\uDE00 " ) ;
      mBuilder.setContentText( "Something important!" ) ;
      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()) ;
   }
}

주요 메서드 살펴보기

  • setContentTitle() : 알림의 제목을 설정합니다.
  • setContentText() : 알림의 본문 내용을 설정합니다.
  • setSmallIcon() : 상태 표시줄에 나타날 작은 아이콘을 지정합니다.
  • setAutoCancel(true) : 사용자가 알림을 탭하면 해당 알림이 자동으로 삭제됩니다.
  • createNotificationChannel() : 안드로이드 8.0 오레오(API 26) 이상에서는 반드시 알림 채널을 먼저 생성해야 알림을 표시할 수 있습니다.

4단계 — AndroidManifest.xml 설정

마지막으로 AndroidManifest.xml에 아래 코드를 추가합니다. 여기서는 진동 권한(android.permission.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>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 직접 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭한 뒤, 목록에서 자신의 모바일 기기를 선택합니다. 그러면 기기에 앱이 설치·실행되며 기본 화면이 표시됩니다. 화면 중앙의 버튼을 누르면 상태 표시줄에 알림이 생성되는 것을 확인할 수 있습니다.