Android 13:为何前台服务仍需在Manifest中声明POST_NOTIFICATIONS权限?
关于Android 13前台服务与POST_NOTIFICATIONS权限的疑问
依据Android官方文档说明:
注:应用启动前台服务无需请求POST_NOTIFICATIONS权限,但仍需像旧版本一样在启动前台服务时添加通知。
我的需求是启动带有可见通知UI的前台服务,通知UI需包含暂停/停止前台服务的控件。
在Android 13中,areNotificationsEnabled()方法默认返回false,官方说明:
若用户在Android 13及以上设备安装应用,通知默认关闭。
对应的判断代码如下:
public static boolean areNotificationsEnabled() { Context context = Application.instance(); final boolean areNotificationsEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled(); return areNotificationsEnabled; }
为确保该方法返回true,我需要启动Settings.ACTION_APP_NOTIFICATION_SETTINGS页面引导用户手动开启通知。
启动Settings.ACTION_APP_NOTIFICATION_SETTINGS的代码
public static void launchActionAppNotificationSettings(Fragment fragment, int requestCode) { try { fragment.startActivityForResult(getLaunchActionAppNotificationSettingsIntent(fragment.getContext()), requestCode); } catch (android.content.ActivityNotFoundException e) { Log.e(TAG, "", e); } } private static Intent getLaunchActionAppNotificationSettingsIntent(Context context) { Intent intent = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS); intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ intent = new Intent("android.settings.APP_NOTIFICATION_SETTINGS"); intent.putExtra("app_package", context.getPackageName()); intent.putExtra("app_uid", context.getApplicationInfo().uid); } else { intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("package:" + context.getPackageName())); } return intent; }
Settings.ACTION_APP_NOTIFICATION_SETTINGS页面UI

请注意截图中红圈标注的按钮。我发现如果不在AndroidManifest.xml中添加POST_NOTIFICATIONS权限,即使多次点击该按钮也无法开启通知。
我的疑问:这是否意味着,即使无需在运行时请求POST_NOTIFICATIONS权限,仍需在AndroidManifest.xml中声明它以支持前台服务?
内容的提问来源于stack exchange,提问作者Cheok Yan Cheng
相关产品推荐
相关产品推荐

