Android获取应用是否开启通知栏及跳转到设置界面

判断通知权限

方式一

在代码中通过NotificationManagerCompat包获取是否打开了通知显示权限:

1
2
NotificationManagerCompat manager = NotificationManagerCompat.from(App.getInstance().getContext());
boolean isOpened = manager.areNotificationsEnabled();

NotificationManagerCompat位于v4包内,所以需要引入v4包。

要注意的是,areNotificationsEnabled方法的有效性官方只最低支持到API 19,低于19的仍可调用此方法不过只会返回true,即默认为用户已经开启了通知。 查了各种资料,目前暂时没有办法获取19以下的系统是否开启了某个App的通知显示权限。

方式二

通过反射获取通知栏是否显示

最低支持到API 19,android8.0上返回的都是true

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
40
41
42
/**
* 获取通知栏权限是否开启
*
*/

public class NotificationsUtils {
private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

@SuppressLint("NewApi")
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 = (Integer) opPostNotificationValue.get(Integer.class);
return ((Integer) 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;
}
}

打开应用详情界面

1
2
3
4
5
6
// 根据isOpened结果,判断是否需要提醒用户跳转AppInfo页面,去打开App通知权限
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", App.getInstance().getApplication().getPackageName(), null);
intent.setData(uri);
startActivity(intent);

打开应用通知设置界面

1
2
3
4
5
6
7
8
9
10
11
12
13
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getActivity().getPackageName());
intent.putExtra("app_uid", getActivity().getApplicationInfo().uid);
startActivity(intent);
} else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
startActivity(intent);
}
坚持原创技术分享,您的支持是对我最大的鼓励!