Flamur Dervishi
Flamur Dervishi

Reputation: 338

Filter AppCenter push notifications depending on the current logged in user

Using AppCenter I am able to send push notification to all my devices with my Xamarin Forms (android only) app.

Since my devices, are going to be shared, I can't do the filter of the notifications on the AppCenter side based on the devices IDs.

I need to make the filter based on the current logged in user to my application. For this with the push notification I also send the WorkerID, which serves as a filter.

While I'm able to do this filter when the app is in foreground, its not working when the app is in background or not running.(normal behaviour since the push event is in App Start)

protected override void OnStart()
{
   // This should come before AppCenter.Start() is called
   // Avoid duplicate event registration:
   if (!AppCenter.Configured)
   {
       Push.PushNotificationReceived += (sender, e) =>
       {
           var title = e.Title;
           var message = e.Message;

           // If app is in background title and message are null
           // App in foreground
           if (!string.IsNullOrEmpty(title))
           {
               foreach (string key in e.CustomData.Keys)
               {
                   if (e.CustomData[key] == Settings.WorkerID)
                   {
                      Current.MainPage.DisplayAlert(title, message, "OK");                                
                   }
               }
           }
        };
   }

   // Handle when your app starts
   AppCenter.Start("android=xxxxxxxxxxxxxxxxxx", typeof(Push));
}

Is there a way to intercept and filter the push notifications when the app is in background and block them when the app is not running (since no user is yet logged in) ?

Upvotes: 0

Views: 464

Answers (2)

nevermore
nevermore

Reputation: 15786

Through the document, you can enable-or-disable-push-at-runtime, so can enable or disable push when use go to background or go back to foreground, like this:

protected override void OnSleep()
{
    // Handle when your app sleeps
    Push.SetEnabledAsync(false);
}

protected override void OnResume()
{
    // Handle when your app resumes
    Push.SetEnabledAsync(true);           
}

You can also enable or disable push when user login or login out:

public void userLogin() {
    Push.SetEnabledAsync(true);
}

public void userLoginOut() {
    Push.SetEnabledAsync(false);
}

Set it in the right place to meet your requirement.

Upvotes: 1

Ruslan U
Ruslan U

Reputation: 26

To filter users when sending push notifications it's preferable to set user id:

AppCenter.SetUserId("your-user-id");

Then on the appcenter.ms go to Push > Send notificaiton. Fill in the required fields. And then in the second step select User list instead of All registered devices. Then enter user ids, separated by commas.

Upvotes: 1

Related Questions