Skip to content
DeveloperMemos

Disabling OneSignal Notifications in Android Applications

OneSignal, Android, Push Notifications1 min read

Push notifications are an essential part of engaging users in mobile applications. OneSignal is a popular service for managing these notifications. However, there might be scenarios where you need to disable notifications, such as when a user logs out of your application or when they turn them off in your settings. This article explains how to programmatically disable OneSignal notifications in an Android app.

Disabling Notifications for Non-Logged-In Users

To ensure that only logged-in users receive notifications, you need to disable OneSignal when a user logs out. Here's how to do it:

Step 1: Initialize OneSignal

First, ensure you have initialized OneSignal in your application. This is typically done in the onCreate method of your Application or main Activity class:

1OneSignal.initWithContext(this, "APP_ID_GOES_HERE")

You might also need to show a pop up for users to approve notifications these days(from Android 13 onwards). OneSignal's documentation recommends doing it like this:

1CoroutineScope(Dispatchers.IO).launch {
2 OneSignal.Notifications.requestPermission(true)
3}

Of course if you have access to the Activity's scope you should use that instead in my opinion.

Step 2: Disable Notifications on Logout

When a user logs out, you can disable OneSignal notifications by opting out of push subscriptions. Add the following code to your logout method:

1OneSignal.User.pushSubscription.optOut()

This code ensures that the user will no longer receive push notifications until they log in again and the notifications are explicitly re-enabled.

Step 3: Re-enable Notifications on Login

When a user logs back in, you'll want to re-enable notifications. To do this, use the following code:

1OneSignal.User.pushSubscription.optIn()

This code opts the user back into receiving push notifications.

About Java Support

The project I was working on when I had to figure this all out still had some Java files. I couldn't figure out a way to access `OneSignal.User`` from Java... Maybe it isn't accessible ata all and you need to use Kotlin I'm not really sure. In the end I ended up creating a helper class with @JvmStatic annotations and called that from Java.

Additional Tips

  • Testing: Always test the enable/disable functionality thoroughly to ensure a smooth user experience.
  • User Preferences: Consider adding an in-app setting to allow users to manage their notification preferences.
  • Server-Side Control: For advanced use cases, consider managing notification subscriptions server-side based on user login status.