在Android 13中,启动带通知的前台服务时,如何正确地确保通知已启用?

6qfn3psc  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(187)

我们希望在Android13(API 33)中启动一个带有通知的前台服务
从Android 13开始,以下函数将返回false,对于第一次用户。
基于https://developer.android.com/develop/ui/views/notifications/notification-permission
如果用户在运行Android 13或更高版本的设备上安装您的应用,则默认情况下,您的应用的通知处于关闭状态。

public static boolean areNotificationsEnabled() {
    Context context = Application.instance();

    final boolean areNotificationsEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled();

    return areNotificationsEnabled;
}

字符串
基于https://developer.android.com/develop/ui/views/notifications/notification-permission,前台服务不需要请求POST_NOTIFICATIONS权限。
如果是这样的话,我可以知道什么是正确的流程,以确保areNotificationsEnabled函数返回true吗?
启动通知活动是否是正确的流程?

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;
}

guicsvcw

guicsvcw1#

为了确保统一的行为,我建议
1.在清单中添加发布通知权限

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

字符串
1.像往常一样请求运行时权限:

private static final int REQUEST_CODE_PERMISSIONS = 111;

if (ContextCompat.checkSelfPermission(YourActivity.this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
       ActivityCompat.requestPermissions(YourActivity.this, new String[]{Manifest.permission.POST_NOTIFICATIONS},REQUEST_CODE_PERMISSIONS);
       }

相关问题