1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package android.support.v4.app; 17 18import android.app.AppOpsManager; 19import android.content.Context; 20import android.content.pm.ApplicationInfo; 21 22import java.lang.reflect.Field; 23import java.lang.reflect.InvocationTargetException; 24import java.lang.reflect.Method; 25 26class NotificationManagerCompatKitKat { 27 private static final String CHECK_OP_NO_THROW = "checkOpNoThrow"; 28 private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION"; 29 30 public static boolean areNotificationsEnabled(Context context) { 31 AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); 32 ApplicationInfo appInfo = context.getApplicationInfo(); 33 String pkg = context.getApplicationContext().getPackageName(); 34 int uid = appInfo.uid; 35 try { 36 Class<?> appOpsClass = Class.forName(AppOpsManager.class.getName()); 37 Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, 38 Integer.TYPE, String.class); 39 Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION); 40 int value = (int) opPostNotificationValue.get(Integer.class); 41 return ((int) checkOpNoThrowMethod.invoke(appOps, value, uid, pkg) 42 == AppOpsManager.MODE_ALLOWED); 43 } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException | 44 InvocationTargetException | IllegalAccessException | RuntimeException e) { 45 return true; 46 } 47 } 48} 49