NotificationBuilder로 알림 구현하기
이 예제는 안드로이드에서 NotificationBuilder를 사용해 알림(Notification)을 생성하는 방법을 단계별로 보여줍니다. 특히 안드로이드 8.0 오레오(API 26)부터는 반드시 알림 채널(Notification Channel)을 등록해야 알림이 정상적으로 표시되므로, OS 버전에 따른 분기 처리 방법도 함께 다룹니다.
1단계 – 새 프로젝트 만들기
Android Studio에서 File ⇒ New Project를 선택한 뒤, 프로젝트 생성에 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.
2단계 – res/layout/activity_main.xml 작성
레이아웃 파일에 아래 코드를 추가합니다. 화면 한가운데에 'create notification' 버튼 하나를 배치하고, 클릭 시 createNotification() 메서드가 호출되도록 구성했습니다.
<? 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 작성
메인 액티비티에 다음 코드를 추가합니다. 빌더에 제목·본문·작은 아이콘을 지정하고 setAutoCancel(true)로 알림을 탭하면 자동으로 사라지도록 했습니다. 또한 오레오(API 26) 이상 버전에서는 중요도(IMPORTANCE_HIGH)를 가진 알림 채널을 먼저 생성한 후 알림을 게시하도록 처리했습니다.
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()) ;
}
}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> </application> </manifest>
알림 표시 가능 여부 확인하기
알림이 실제로 사용자에게 표시될 수 있는지 확인하려면 NotificationManagerCompat의 areNotificationsEnabled() 메서드를 활용하면 됩니다. 이 값이 false라면 사용자가 앱의 알림을 차단한 상태이므로, 설정 화면으로 안내해 알림 권한을 다시 허용하도록 유도하는 것이 좋습니다.
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
if (!manager.areNotificationsEnabled()) {
// 알림이 차단된 상태 → 설정 화면으로 유도
Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(intent);
}또한 앱 전체가 아니라 개별 채널이 차단된 경우도 있으므로 함께 점검해야 합니다. NotificationChannel의 getImportance() 반환값이 IMPORTANCE_NONE이라면 해당 채널의 알림은 표시되지 않습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결한 상태라고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 실행 기기 목록에서 본인의 휴대폰을 선택하면 앱의 기본 화면이 나타나고, 버튼을 누를 때마다 새로운 알림이 상태 표시줄에 생성되는 것을 확인할 수 있습니다.