Xamarin.Android单击Android锁屏通知,打开页面并将通知正文传递给它

时间:2018-08-10 23:54:09

标签: xamarin.forms push-notification xamarin.android

我是一名初级开发人员,现在我被困住了。

基本上,我有一个LoginPage.Xaml.cs,它第一次在本地存储用户,如果该用户下次存在,则在App.xaml.cs中加载HomePage.xaml.cs而不是Login.xaml。 .cs页面。

HomePage.xaml.cs订阅了接收通知,并且包含显示通知的代码。

当我单击iOS LockScreen上的通知时,将加载HomePage.xaml.cs,并传递并显示通知正文。

当我在Android锁屏上单击通知时,会加载HomePage.xaml.cs,但通知不会传递,并且没有任何显示。

是否还应订阅App.xaml.cs并将通知传递给HomePage.xaml.cs?我尝试了但没用。

请随意批评以下与问题相关或无关的代码。

//Android Project (Services folder class)
[Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
        public const string PRIMARY_CHANNEL_ID = "com.company.saapp.urgent";

        public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);

            Console.WriteLine("Received: " + message);

            // Pull message body out of the template
            var messageBody = message.Data["message"];
            if (string.IsNullOrWhiteSpace(messageBody))
                return;

            if (isApplicationInTheBackground())
            {
                if ((int)Android.OS.Build.VERSION.SdkInt >= 26)
                {
                    sendNotificationForAndroidOreo(messageBody);
                }
                else
                {
                    sendNotificationForAndroid(messageBody);
                }
            }

            try
            {

                //pass message to xamarin forms, the picked up by main page and update the label if app is active
                MessagingCenter.Send<object, string>(this, ShakeAlarmRR1.App.NotificationReceivedKey, messageBody);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error extracting message: " + ex);
            }
        }


        private void sendNotificationForAndroid(string messageBody)
        {
            // push notifications for API level < Oreo
            var title = "Urgent message";

            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            try
            {
                var notificationBuilder = new NotificationCompat.Builder(this)
                    .SetSmallIcon(Resource.Drawable.notification_action_background)
                    .SetContentTitle(title)
                    .SetContentText(messageBody)
                    .SetContentIntent(pendingIntent)
                    .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                    .SetVisibility(NotificationCompat.VisibilityPublic)
                    .SetAutoCancel(true);

                var notificationManager = NotificationManager.FromContext(this);
                notificationManager.Notify(0, notificationBuilder.Build());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
            }
        }

        private void sendNotificationForAndroidOreo (string messageBody)
        {
            // for changing focus to app when notification clicked
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            // push notifications for Api level >= 26
            var title = "Urgent message";
            var notificationId = 0;

            try
            {
                //var notifMessage = messageBody.GetNotification().Body;
                var notificationBuilder = new Notification.Builder(ApplicationContext, PRIMARY_CHANNEL_ID)
                                  .SetContentTitle(title)                     
                                  .SetContentText(messageBody)
                                  .SetContentIntent(pendingIntent)      // added for tap to go to app
                                  .SetSmallIcon(Resource.Drawable.notification_icon_background)
                                  .SetAutoCancel(true);

                var manager = (NotificationManager)GetSystemService(NotificationService);
                manager.Notify(notificationId, notificationBuilder.Build());

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
            }
        }

        private bool isApplicationInTheBackground()
        {
            bool isInBackground;

            RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
            ActivityManager.GetMyMemoryState(myProcess);
            isInBackground = myProcess.Importance != Android.App.Importance.Foreground;

            return isInBackground;
        }
    }


//HomePage.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {

        public HomePage ()
        {
            InitializeComponent ();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            MessagingCenter.Subscribe<object, string>(this, App.NotificationReceivedKey, OnMessageReceived);

        }

        private void OnMessageReceived(object sender, string msg)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                LabelNotificationBody.Text = msg;
            });
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            MessagingCenter.Unsubscribe<object>(this, App.NotificationReceivedKey);
        }


    }


// app.xaml.cs
public partial class App : Application
    {
        public static MobileServiceClient MobileService =
              new MobileServiceClient( "https://myapp.azurewebsites.net");

        public const string NotificationReceivedKey = "NotificationReceived";

        // url of the web api published to Azure
        public const string MobileServiceUrl = "https://mywebapi.azurewebsites.net";

        public static string DatabaseLocation = string.Empty;

        // this will store the local user from local database for auto-login
        User LoggedInUser = new User();

        public App ()
        {
            InitializeComponent();

            MainPage = new NavigationPage (new LoginPage());
        }

        // overloaded constructor, for using local database with sql lite
        public App(string databaseLocation)
        {
            InitializeComponent();

            DatabaseLocation = databaseLocation;

            // read from the database, if user exists locally skip the login page
            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
            {
                conn.CreateTable<LocallyStoredUser>();
                var localUsers = conn.Table<LocallyStoredUser>().ToList();
                if (localUsers.Count > 0)
                {
                    LoggedInUser.Email = localUsers.FirstOrDefault<LocallyStoredUser>().Email;
                    LoggedInUser.NodeId = localUsers.FirstOrDefault<LocallyStoredUser>().NodeId;

                    MainPage = new NavigationPage(new QuakeDetectionPage());
                }
                else
                {
                    MainPage = new NavigationPage(new LoginPage());
                }
            }
        }


        protected override void OnStart ()
        {
            // Handle when your app starts
        }

        protected override void OnSleep ()
        {
                       // Handle when your app starts
        }

        protected override void OnResume ()
        {
            // Handle when your app resumes
        }
    }

0 个答案:

没有答案