Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Android App crashes after receiving push notification

$
0
0

Specifically, after I swipe the app off of recents, and send a notification using GCM, I receive "Unfortunately, MyApp has stopped working.". In fact, I receive this message twice for some reason, the second time comes about 10 seconds after clicking 'Ok' on the first one.

Notifications are working correctly when the app is running (foreground and background), its only after swiping it off screen do I get this error. I am able to receive notifications after I close the app if I use Baidu Push, so I know it should be possible with GCM too.

Here is the code that is causing the crash:

    [Service(Name = "my.pkg.name.MyGcmListenerService", Exported = true), 
        IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })]
    public class MyGcmListenerService : GcmListenerService
    {
        const string TAG = "MyGcmListenerService";

        public override void OnMessageReceived(string from, Bundle data)
        {
            // If I uncomment this try catch block, the crash doesn't happen. 
            // But I still receive no notification, as there is still an exception occurring.
            // Also, the LogManager class writes the error to a .txt file, however if the 
            // app is swiped off screen, it doesn't write to that file, so I don't know
            // exactly what the error is.

            //try
            //{
                CreateNotification("msg title", "new message!!!");
            //}
            //catch (Exception ex)
            //{
            //    LogManager.Instance.Log("MyGcmListenerService - OnMessageReceived ERROR: " + ex.ToString());
            //}
        }

        private void CreateNotification(string title, string message)
        {
            var intent = new Intent(Xamarin.Forms.Forms.Context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(Xamarin.Forms.Forms.Context, 
                0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new NotificationCompat.Builder(Xamarin.Forms.Forms.Context)
                .SetSmallIcon(Resource.Drawable.icon)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetAutoCancel(true)
                .SetContentIntent(pendingIntent);

            var notificationManager = 
                (NotificationManager)Xamarin.Forms.Forms.Context.GetSystemService(
                    Android.Content.Context.NotificationService);

            notificationManager.Notify(0, notificationBuilder.Build());
        }

    }

Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>