Home > OS >  How to opt-out from Firebase Notifications (Cloud Messaging)
How to opt-out from Firebase Notifications (Cloud Messaging)

Time:06-24

referring to Unity project that's targeting both Android and IOS. Unity - 2020.3.22f1 (LTS) Firebase SDK - 9.0.0

Trying to implement Firebase push notifications (Cloud Messaging) and having issues with allowing the user to opt-out of those notifications. I've tried removing the messageReceived event listener which didn't work, the client still received a push notification.

This is how I initialize all of my Firebase APIs including messaging -

//firebase
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
    //init analytics
    FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);

    //init auth
    Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
    auth.SignInAnonymouslyAsync().ContinueWithOnMainThread(task => {
        if (task.IsCanceled || task.IsFaulted) {
            return;
        }
            
        //if authentication worked init rtdb
        DatabaseReference = FirebaseDatabase.DefaultInstance.RootReference;
    });
        
    //if never initialized before init notifications
    if (PlayerPrefs.GetInt("NotificationsFirstLaunch") == 0)
    {
        //ios permission, should only be invoked once
        Firebase.Messaging.FirebaseMessaging.RequestPermissionAsync().ContinueWithOnMainThread(task => { });
        EnableNotifications();
        PlayerPrefs.SetInt("NotificationsFirstLaunch", 1);
        PlayerPrefs.Save();
    }
});

public static void EnableNotifications()
{
    Firebase.Messaging.FirebaseMessaging.TokenReceived  = OnTokenReceived;
    Firebase.Messaging.FirebaseMessaging.MessageReceived  = OnMessageReceived;
    PlayerPrefs.SetInt("Notifications", 1);
    PlayerPrefs.Save();
}

public static void DisableNotification()
{
    Firebase.Messaging.FirebaseMessaging.TokenReceived -= OnTokenReceived;
    Firebase.Messaging.FirebaseMessaging.MessageReceived -= OnMessageReceived;
    PlayerPrefs.SetInt("Notifications", 0);
    PlayerPrefs.Save();
}

public static void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token) {
    Debug.Log("Received Registration Token: "   token.Token);
}

public static void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e) {
    Debug.Log("Received a new message from: "   e.Message.From);
}

My AndroidManifest was adjusted to use Firebase entry point like such -

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.unity3d.player" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" tools:node="remove" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove" />
  <application android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="false">
    <activity android:name="com.google.firebase.MessagingUnityPlayerActivity" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
    <service android:name="com.google.firebase.messaging.MessageForwardingService"
     android:permission="android.permission.BIND_JOB_SERVICE"
     android:exported="false" >
    </service>
......
  </application>
</manifest>

So basically I have a toggle in my game settings that calls EnableNotifications/DisableNotification.

I've tried using Topics with Subscribe/UnSubscribe but that didn't work as well.

Would appreciate guidance, looking for a solution online just resulted in multiple posts of bugs that never got resolved... Thanks

CodePudding user response:

Adding and removing the listeners from the event didn't help as the token is being received upon app launch anyways, removing it afterward had no effect.

The goto approach to achieve such behavior is indeed using topics with Subscribe/Unsubscribe methods. Problem is that the approach above is bugged upon second app launch, when testing the Unsubscribe isn't being processed although no exceptions are presented.

The solution I found was refreshing the token upon every subscription/unsubscription.

Example -

public static void EnableNotifications()
{
    Firebase.Messaging.FirebaseMessaging.TokenReceived  = OnTokenReceived;
    Firebase.Messaging.FirebaseMessaging.MessageReceived  = OnMessageReceived;

    //init notifications
    Firebase.Messaging.FirebaseMessaging.DeleteTokenAsync().ContinueWithOnMainThread(task =>
    {
        Debug.Log($"FirebaseManager - Deleted Token");
        Firebase.Messaging.FirebaseMessaging.GetTokenAsync().ContinueWithOnMainThread(task =>
        {
            Debug.Log($"FirebaseManager - Got New Token");
            Firebase.Messaging.FirebaseMessaging.SubscribeAsync(DefaultTopic).ContinueWithOnMainThread(task => {
                Debug.Log($"FirebaseManager - Subscribed To Topic - {DefaultTopic}");
            });
        });
    });
    PlayerPrefs.SetInt("Notifications", 1);
    PlayerPrefs.Save();
}
public static void DisableNotification()
{
    //init notifications
    Firebase.Messaging.FirebaseMessaging.DeleteTokenAsync().ContinueWithOnMainThread(task =>
    {
        Debug.Log($"FirebaseManager - Deleted Token");
        Firebase.Messaging.FirebaseMessaging.GetTokenAsync().ContinueWithOnMainThread(task =>
        {
            Debug.Log($"FirebaseManager - Got New Token");
            Firebase.Messaging.FirebaseMessaging.UnsubscribeAsync(DefaultTopic).ContinueWithOnMainThread(task => {
                Debug.Log($"FirebaseManager - UnSubscribed To Topic - {DefaultTopic}");
            });
        });
    });
    
    PlayerPrefs.SetInt("Notifications", 0);
    PlayerPrefs.Save();
}
  • Related