CustomView로 Android Notification 띄우기

현재 Android 7.0까지 나온 상황에서
6.0 이상에 추가된 Notification의 모든 기능을 활용하는 코드는 아니지만
5.0 부터 추가된 Headup Notification까지는 포함하는 코드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public static int showNotification(Context context, int iconResId, RemoteViews view, RemoteViews bigView, Class activityCls) {
    Notification.Builder builder = new Notification.Builder(context)
            .setSmallIcon(iconResId)
            .setWhen(System.currentTimeMillis())
            .setPriority(Notification.PRIORITY_MAX)
            .setFullScreenIntent(getIntent(context, activityCls), true)
            .setContentIntent(getIntent(context, activityCls));
    Notification notification = null;
 
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        builder.setCustomContentView(view);
        if(bigView != null) {
            builder.setCustomBigContentView(bigView);
        }
        notification = builder.build();
    } else  {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification = builder.build();
            if(bigView != null) {notification.bigContentView = bigView;}
        } else {
            notification = new Notification(iconResId, context.getString(R.string.app_name), System.currentTimeMillis());
            notification.contentIntent = getIntent(context, activityCls);
        }
 
        notification.contentView = view;
    }
 
    // Because clicking the notification opens a new ("special") activity, there's
    // no need to create an artificial back stack.
 
    // Sets an ID for the notification
    int mNotificationId = BASE_NOTIFICATION_ID + (int)(Math.random()*100);
    // Gets an instance of the NotificationManager service
    NotificationManagerCompat mgr = NotificationManagerCompat.from(context);
    // Builds the notification and issues it.
    mgr.notify(mNotificationId, notification);
 
    return mNotificationId;
}
cs


OS버전별로 어느정도 분기가 되어있고,
CustomView를 이용해 Small View와 BigView의 처리도 할 수 있고
Headup Notification도 가능하다.

Headup Notification은
기본적으로 setPriority()를 MAX 혹은 HIGH로 해줘야 하고,
setFullScreenIntent()를 넣어줘야 가능하다.
setAutoCancel()를 해주면 시간이 지났을때 자동 취소가 되기도 한다.

댓글

이 블로그의 인기 게시물

[Android] DataBinding의 동작방식 - 4. include Tag 혹은 ViewStub 사용시의 Binding

[Android] Retrofit2, OkHttpClient Method 정리

[Android] Layout별 성능 비교[Measure 호출횟수 비교] (LinearLayout vs RelativeLayout vs ConstraintLayout)