最近,安卓13已经发布了。安装13显著的新特质仍然是聚焦与个人隐私保护和安全。

通知栏消息一直是App和用户沟通的有效渠道。

在Android13之前,App只需要使用NotificationManager即可向终端用户推送通知栏消息

。Android13则引入了新的运行时通知权限:POST_NOTIFICATIONS。对此,App开发者需要予以重点关注。

Android通知权限 手机通知权限_android

 

如果是TargetSdk<33的情况下:

开发者只需要向之前一样的申请权限,当App使用通知栏功能时,系统将自动弹出授权弹窗:用于点击弹出的权限窗口就可以了

 

再看TargetSdk == 33的情况。

开发者需要在AndroidManifest.xml中声明POST_NOTIFICATIONS权限,还需要在使用通知栏推送功能时在代码中申请运行时权限:

requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"})以上是用户点击"允许"App推送的情况。当然,用户也有可能点击"不允许"。值得注意的是,一旦被用户拒绝授权,下次系统将不会再出现权限申请的弹窗。如果App仍然要推送重要消息(比如重大版本更新)给用户,则需要引导用户前往设置界面打开通知权限。代码如下:

@Override
protected void onResume() {
    super.onResume();
    findViewById(R.id.button7).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          jumpNotificationSetting();
        }
    });
}

private void jumpNotificationSetting() {
    final ApplicationInfo applicationInfo = getApplicationInfo();
    try {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
        intent.putExtra("app_package", applicationInfo.packageName);
        intent.putExtra("android.provider.extra.APP_PACKAGE", applicationInfo.packageName);
        intent.putExtra("app_uid", applicationInfo.uid);
        startActivity(intent);
    } catch (Throwable t) {
        t.printStackTrace();
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.fromParts("package", applicationInfo.packageName, null));
        startActivity(intent);
    }
}

如果App要确认用户是否已启用通知,可以调用NotificationManager.areNotificationsEnabled()进行判断
如果仍然需要通知权限,就可以用上述的代码进行继续向系统申请通知权限。