简体   繁体   English

当App未运行时,Xamarin.Android推送通知正在破坏应用程序

[英]Xamarin.Android push notification is breaking the app when App is Not Running

I am trying to add push notifications to my app by the following https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm 我试图通过以下https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm向我的应用添加推送通知

After following this step-by-step tutorial to setup the Push Notification on Xamarin.Android, the Android devices receive push notifications when the app is running or backgrounded. 按照此分步教程在Xamarin.Android上设置推送通知后,Android设备会在应用程序运行或后台运行时收到推送通知。 But if I close the app so that it is no longer running, and then send a push notification, the device shows this error message: 但是,如果我关闭应用程序以使其不再运行,然后发送推送通知,则设备会显示以下错误消息:

“Unfortunately, [App Name] has stopped” “不幸的是,[App Name]已停止”

图片

Here goes my code implementation.. 这是我的代码实现..

[Service] // Must use the service tag
public class PushHandlerService : GcmServiceBase
{
    public static string RegistrationID { get; private set; }
    private NotificationHub Hub { get; set; }

    public PushHandlerService() : base(Constants.SenderID)
    {
        Log.Info(MyBroadcastReceiver.TAG, "PushHandlerService() constructor");
    }

    protected override void OnRegistered(Context context, string registrationId)
    {
        Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
        RegistrationID = registrationId;

        /*createNotification("PushHandlerService-GCM Registered...",
                            "The device has been Registered!");*/

        Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString,
                                    context);
        try
        {
            Hub.UnregisterAll(registrationId);
        }
        catch (Exception ex)
        {
            Log.Error(MyBroadcastReceiver.TAG, ex.Message);
        }

        //var tags = new List<string>() { "falcons" }; // create tags if you want
        var tags = new List<string>() { };

        try
        {
            var hubRegistration = Hub.Register(registrationId, tags.ToArray());
        }
        catch (Exception ex)
        {
            Log.Error(MyBroadcastReceiver.TAG, ex.Message);
        }
    }
    protected override void OnMessage(Context context, Intent intent)
    {
        Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");

        var msg = new System.Text.StringBuilder();

        if (intent != null && intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
                msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
        }

        string messageText = intent.Extras.GetString("message");
        if (!string.IsNullOrEmpty(messageText))
        {
            createNotification("New hub message!", messageText);
        }
        else
        {
            createNotification("Unknown message details", msg.ToString());
        }
    }
    void createNotification(string title, string desc)
    {
        //Create notification
        var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

        //Create an intent to show UI
        var uiIntent = new Intent(this, typeof(MainActivity));

        //Create the notification
        var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title);

        //Auto-cancel will remove the notification once the user touches it
        notification.Flags = NotificationFlags.AutoCancel;

        //Set the notification info
        //we use the pending intent, passing our ui intent over, which will get called
        //when the notification is tapped.
        notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));

        //Show the notification
        notificationManager.Notify(1, notification);
        dialogNotify(title, desc);
    }

    protected void dialogNotify(string title, string message)
    {
        MainActivity.instance.RunOnUiThread(() => {
            AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.instance);
            AlertDialog alert = dlg.Create();
            alert.SetTitle(title);
            alert.SetButton("Ok", delegate {
                alert.Dismiss();
            });
            alert.SetMessage(message);
            alert.Show();
        });
    }

    protected override void OnUnRegistered(Context context, string registrationId)
    {
        Log.Verbose(MyBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId);

        createNotification("GCM Unregistered...", "The device has been unregistered!");
    }

    protected override bool OnRecoverableError(Context context, string errorId)
    {
        Log.Warn(MyBroadcastReceiver.TAG, "Recoverable Error: " + errorId);

        return base.OnRecoverableError(context, errorId);
    }

    protected override void OnError(Context context, string errorId)
    {
        Log.Error(MyBroadcastReceiver.TAG, "GCM Error: " + errorId);
    }
}

}` }`

Finally I Fixed the Issue by making async of the method OnMessage 最后,我通过对方法OnMessage进行异步来修复问题

Here the Code is: 这里的守则是:

    protected override async void OnMessage(Context context, Intent intent)
    {
    Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");
        await Task.Delay(1000);

        var msg = new System.Text.StringBuilder();
        if (intent != null && intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
                msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
        }

        string messageText = intent.Extras.GetString("message");
        if (!string.IsNullOrEmpty(messageText))
        {
           createNotification("New hub message!", messageText);
        }
        else
        {
           createNotification("Unknown message details", msg.ToString());
        }
    }`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当应用退出时,将远程通知(GCM)迁移到Xamarin.Android(monodroid)中 - Remote notification (GCM) into Xamarin.Android (monodroid) when app exit Xamarin.Android如何使“ wav”文件成为应用程序的默认推送通知声音? - Xamarin.Android How to make a 'wav' file the default push notification sound for the app? Xamarin.Android:点击通知会导致整个应用程序空白 - Xamarin.Android: Clicking on Notification Causes Whole App to Blank 在模拟器中运行的Xamarin.Android应用中使用Realm会引发RealmFileAccessErrorException - Using Realm in Xamarin.Android app running in emulator throws RealmFileAccessErrorException 当应用程序被杀死时扫描 Xamarin.android 中的 ibeacon 不起作用 - Scaning ibeacon in Xamarin.android when app is killed is not working 将 Kotlin 应用程序转换为 Xamarin.Android 应用程序 - Converting Kotlin app to Xamarin.Android application Xamarin.Android与控制台应用程序(Websockets)通信 - Xamarin.Android communicate with Console app (Websockets) Visual Studio无法调试Xamarin.Android应用 - Visual studio is not debuging Xamarin.Android app Xamarin.Android:以编程方式更改应用程序语言? - Xamarin.Android : change app language programmatically? 当我的 Xamarin Android 应用程序停止时,如何接收推送通知? - How can I receive a Push Notification when my Xamarin Android app is stopped?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM