본문 바로가기
안드로이드/코틀린

Android - 시스템 앱 알림 상태 확인

by 나이아카 2023. 10. 25.

 회사에서 작업하다가 찾는데 시간이 좀 걸린 부분이 있어 기억하려고 올리는 글입니다. 그래서 짧습니다.


 첫 번째로 시스템 알림의 on/off 여부 확인 코드입니다.

val isEnable = NotificationManagerCompat.from(context).areNotificationsEnabled()

위 코드의 isEnable이 true이면 시스템 알림이 켜져있는 상태, false이면 꺼져있는 상태입니다. 단, 안드로이드 버전에 따라 알림 부분이 조금 달라지는데, areNotificationsEnabled()를 보면 

/**
 * Returns whether notifications from the calling package are not blocked.
 */
public boolean areNotificationsEnabled() {
    if (Build.VERSION.SDK_INT >= 24) {
        return mNotificationManager.areNotificationsEnabled();
    } else if (Build.VERSION.SDK_INT >= 19) {
        AppOpsManager appOps =
                (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = mContext.getApplicationInfo();
        String pkg = mContext.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        try {
            Class<?> appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE,
                    Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (int) opPostNotificationValue.get(Integer.class);
            return ((int) checkOpNoThrowMethod.invoke(appOps, value, uid, pkg)
                    == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException
                | InvocationTargetException | IllegalAccessException | RuntimeException e) {
            return true;
        }
    } else {
        return true;
    }
}


 이런식으로 자기네들이 알아서 분기쳐줍니다. 물론 TIRAMISU버전부터는 POST_NOTIFICATION 권한으로 파악하는 것도 가능하지만, 굳이 그렇게 할 이유는 없습니다(권한 허용 팝업을 위한거라면 의미가 있을 수도 있겠네요).

'안드로이드 > 코틀린' 카테고리의 다른 글

Generic 이란  (1) 2023.12.08
(Kotlin) Flow - 1  (0) 2023.08.10
AAC Navigation의 특징  (0) 2023.06.02
JvmStatic 어노테이션  (0) 2023.03.16
Kotlin - Object 키워드(with SingleTon)  (1) 2023.02.17

댓글