简体   繁体   中英

Android push notification from xamarin.forms button click hangs

I've been slowly trying to get into push notifications and start learning about them / implementing them in an app I'm building.

I've been through the tutorials about getting set up with Azure Notification Hub and Firebase, making the connection there, sending a test push, etc. and I have all of that working where I'm able to receive a notification sent from the hub to my app (on my phone). I've also been able to successfully create a console application that pushes a notification to (I'm assuming) the hub which then sends the notification to my app.

What I'm attempting to do, and the cause for this question, is take that same code from the console application and implement it inside a button click method for Xamarin.Forms so I can test out sending a push notification from a button click and also receiving said notification.

Here is my xaml (pretty basic)

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Class="NotificationExample.MainPage">

<StackLayout>
    <!-- Place new controls here -->
    <Label x:Name="Received"
        Text="Welcome to Xamarin.Forms!" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />

    <Button Text="Send Notification"
            Clicked="Button_Clicked"/>
</StackLayout>
</ContentPage>

Here is my code behind for MainPage

[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        MessagingCenter.Subscribe<string>(this, "Update", (sender) =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                Received.Text = sender;
            });
        });
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        SendTemplateNotificationsAsync().GetAwaiter().GetResult();
    }

    private static async Task SendTemplateNotificationsAsync()
    {
        NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(DispatcherConstants.FullAccessConnectionString, DispatcherConstants.NotificationHubName);
        Dictionary<string, string> templateParameters = new Dictionary<string, string>();

        // Send a template notification to each tag. This will go to any devices that
        // have subscribed to this tag with a template that includes "messageParam"
        // as a parameter
        foreach (var tag in DispatcherConstants.SubscriptionTags)
        {
            templateParameters["messageParam"] = $"Test notification {Guid.NewGuid()}";
            try
            {
                await hub.SendTemplateNotificationAsync(templateParameters, tag);
            }
            catch (Exception ex)
            {
            }
        }
    }
}

The code hangs when I call SendTemplateNotificationAsync inside the button clicked method. This same code works flawlessly when called inside a console application and sends the notification.

Is there something different about including it inside a Xamarin.Forms project as opposed to a console app?

The only notable difference is that you are now running on UI thread. And running the long operations on UI thread may freeze and at the end crash the app, which sounds like what is happening to you. If that is the case, run the code inside Task.Run .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM