Scorb
Scorb

Reputation: 1920

Can I check if notifications are on for an app?

In Android and iOS system settings you can toggle notifications on an off for an app after granting permissions.

When I go into Android settings, and turn off notifications for my app, the following code (using flutter_local_notifications) still indicates the app has notification permissions.

    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }

Is there a way to check if the notifications have been turned on or off for an app?

Upvotes: 3

Views: 8667

Answers (3)

Tigran Muradyan
Tigran Muradyan

Reputation: 123

if (await permission.request().isGranted) {
  # code to run if the permissions are granted
}

This works for me.

My Issue was: The way of just checking permission.status, always returns denied for me.

Solution: Just use permission.request()... to check the status of the permission.

The method I have:

Future<void> requestPermission(Permission permission) async {
  if (await permission.request().isGranted) {
    ...
  }
}

In my case, I was using that to show an alert dialog to enable the notifications. You can see the main code that includes the other way of using Permissions:

bool showRequiredNotifAlert = false;

  void checkNotifPermissions() {
    Permission.notification.isGranted.then((value) => setState(() => showRequiredNotifAlert = !value));
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.detached || state == AppLifecycleState.inactive) {
      return;
    }

    if (state == AppLifecycleState.resumed) {
      checkNotifPermissions();
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    checkNotifPermissions();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

Upvotes: -1

MeLean
MeLean

Reputation: 3441

Try this:

if (await  Permission.notification.request().isGranted) {
   //notifications permission is granted do some stuff
}

Upvotes: 2

Xuuan Thuc
Xuuan Thuc

Reputation: 2521

Are you try use permission_handler package

PermissionStatus? statusNotification = Permission.notification.request();

bool isGranted = statusNotification == PermissionStatus.granted

Upvotes: 2

Related Questions