安卓4.1:如何检查通知是应用程序禁用?应用程序、通知

2023-09-11 12:30:38 作者:旧时光的帅气少年

的Andr​​oid 4.1为用户提供了一个复选框以禁用通知特定的应用程序。

Android 4.1 offers the user a check box to disable notifications for a specific application.

然而,作为一个开发者,我们有没有办法知道一个电话,通知是否有效还是无效。

However, as a developer we have no way to know whether a call to notify was effective or not.

我真的需要检查的通知是当前应用程序禁用的,但我找不到API中的任何设置的。

I really need to check if the notifications are disabled for the current application but I can't find any setting for that in the API.

是否有过一种方法来检查,在code此设置?

Is there ever a way to check this setting in the code?

推荐答案

其实这是pretty的容易做的:

Actually this is pretty easy to do:

/**
 * Created by desgraci on 5/7/15.
*/
public class NotificationsUtils {

private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

public static boolean isNotificationEnabled(Context context) {

    AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

    ApplicationInfo appInfo = context.getApplicationInfo();

    String pkg = context.getApplicationContext().getPackageName();

    int uid = appInfo.uid;

    Class appOpsClass = null; /* Context.APP_OPS_MANAGER */

    try {

        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(mAppOps,value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return false;
}
}

干杯