Je crée une application de rappel sur Xamarin et j'essaie de transmettre des notifications.

Pour le moment, au lieu d'envoyer une notification, mon application ouvrira une activité vide, comme ceci : entrez la description de l'image ici

Voici une partie de mon code:

namespace ReminderApp.Models
{
    public class Reminder
    {
        public int Id { get; set; }
        public string Date { get; set; }
        public string Time { get; set; }
        public string Note { get; set; }
        public Reminder()
        {
        }
    }
}

Activité de notification

using Android.App;
using Android.Content;
using Newtonsoft.Json;
using ReminderApp.Models;
using ReminderApp.HelperRepository;
using Android.OS;

namespace ReminderApp.Notifications
{
    [Activity(Label = "ReminderApp")]
    public class ReminderNotifications : Activity
    {
        Reminder reminder;
        public ReminderNotifications()
        {
        }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);


            var channel = new NotificationChannel("dan1414", "FCMDD Notifications", NotificationImportance.Default)
            {
                Description = "Cloud Messages appear in this channel"
            };

            reminder = ReminderHelper.SelectReminder(this);
            if (reminder != null)
            {
                Intent newIntent = new Intent(this, typeof(ReminderContent));
                newIntent.PutExtra("reminder", JsonConvert.SerializeObject(reminder));

                Android.Support.V4.App.TaskStackBuilder stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this);
                stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(ReminderContent)));
                stackBuilder.AddNextIntent(newIntent);

                PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

                Notification.Builder builder = new Notification.Builder(this, channel.Id)
                .SetAutoCancel(true)
                .SetContentIntent(resultPendingIntent)
                .SetContentTitle("Reminder!!")
                .SetSmallIcon(Resource.Drawable.Screenshot_2020_11_11_at_4_57_02_PM)
                .SetContentText("Click for details..");
                //.SetContentInfo("Start");
                NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(channel);
                notificationManager.Notify(0, builder.Build());
            }
        }
    }
}

Code principal:

using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
using Newtonsoft.Json;
using ReminderApp.Models;
using ReminderApp.HelperRepository;
using ReminderApp.Notifications;

namespace ReminderApp
{
    [Activity(Label = "ReminderApp", MainLauncher = true)]
    public class MainActivity : Activity
    {
        public Reminder reminder;
        EditText _dateDisplay;
        EditText _timeDisplay;
        EditText _txtNote;
        Button _saveButton;
        Button _btnList;

        #region DateOperation  
        [Obsolete]
        void DateSelect_OnClick(object sender, EventArgs eventArgs)
        {
            DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
            {
                _dateDisplay.Text = time.ToString().Split(' ')[0];
                reminder.Date = _dateDisplay.Text + " ";
            });
            frag.Show(FragmentManager, DatePickerFragment.TAG);
        }
        #endregion

        #region TimeOperation  
        [Obsolete]
        void TimeSelectOnClick(object sender, EventArgs eventArgs)
        {
            TimePickerFragment frag = TimePickerFragment.NewInstance(
                delegate (DateTime time)
                {
                    _timeDisplay.Text = time.ToShortTimeString();
                    reminder.Time = _timeDisplay.Text + " ";
                });

            frag.Show(FragmentManager, TimePickerFragment.TAG);
        }
        #endregion

        #region SaveDetails  
        void SaveRecords(object sender, EventArgs eventArgs)
        {
            reminder.Note = _txtNote.Text;
            if (Vaidate())
            {
                DateTime currentDT = DateTime.Now;
                DateTime selectedDT = Convert.ToDateTime(reminder.Date + " " + reminder.Time);

                if (selectedDT > currentDT)
                {
                    ReminderHelper.InsertReminderData(this, reminder);
                    ScheduleReminder(reminder);
                    var reminderAdded = new Intent(this, typeof(ReminderAdded));
                    reminderAdded.PutExtra("reminder", JsonConvert.SerializeObject(reminder));
                    StartActivity(reminderAdded);
                }
                else
                {
                    Toast.MakeText(this, "This is invalid selelction of Date, Time!", ToastLength.Short).Show();
                }
            }

        }

        bool Vaidate()
        {
            if (reminder.Date == string.Empty || reminder.Time == string.Empty || reminder.Note == string.Empty)
            {
                Toast.MakeText(this, "Enter the details of all fields!", ToastLength.Short).Show();
                return false;
            }
            return true;
        }
        #endregion

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            reminder = new Reminder();
            _dateDisplay = FindViewById<EditText>(Resource.Id.date_display);
            _timeDisplay = FindViewById<EditText>(Resource.Id.time_display);
            _txtNote = FindViewById<EditText>(Resource.Id.txtNote);

            _saveButton = FindViewById<Button>(Resource.Id.save);
            _btnList = FindViewById<Button>(Resource.Id.btnList);

            _dateDisplay.Click += DateSelect_OnClick;
            _timeDisplay.Click += TimeSelectOnClick;
            _saveButton.Click += SaveRecords;

            _btnList.Click += (sender, e) => {
                StartActivity(new Intent(this, typeof(ListReminder)));
            };
        }

        public void ScheduleReminder(Reminder reminder)
        {
            AlarmManager manager = (AlarmManager)GetSystemService(AlarmService);
            Intent myIntent;
            PendingIntent pendingIntent;
            myIntent = new Intent(this, typeof(ReminderNotifications));
 
            var t = reminder.Time.Split(':');
            var ampm = t[1].Split(' ')[1];
            var hrr = Convert.ToDouble(t[0]);
            var min = Convert.ToDouble(t[1].Split(' ')[0]);

            string dateString = Convert.ToString(reminder.Date + " " + hrr + ":" + min + ":00 " + ampm);

            DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dateString);
            var millisec = dateOffsetValue.ToUnixTimeMilliseconds();

            pendingIntent = PendingIntent.GetActivity(this, 0, myIntent, 0);
            manager.Set(AlarmType.RtcWakeup, millisec, pendingIntent);
        }
    }
}

Activité à ouvrir lorsqu'on clique sur la notification :

using Android.App;  
using Android.Content;  
using Android.OS;  
using Android.Widget;  
using Newtonsoft.Json;  
using ReminderApp.Models;  
using ReminderApp.HelperRepository;  
  
namespace ReminderApp
{
    [Activity(Label = "ReminderContent")]
    public class ReminderContent : Activity
    {
        Reminder reminder;
        TextView _txtNote;
        Button _btnBack;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ReminderContent);

            // Create your application here  
            reminder = JsonConvert.DeserializeObject<Reminder>(Intent.GetStringExtra("reminder"));
            ReminderHelper.DeleteReminder(this, reminder);
            _txtNote = FindViewById<TextView>(Resource.Id.txt_note);
            _txtNote.Text = reminder.Note;
            _btnBack = FindViewById<Button>(Resource.Id.btn_back);
            _btnBack.Click += (sender, e) => {
                StartActivity(new Intent(this, typeof(ListReminder)));
            };
        }
    }
}

Qu'ai-je fait de mal?

Voici mon code complet si besoin : https://github.com/CrazyDanyal1414/ReminderApp

Toute aide appréciée!

1
dan51 17 nov. 2020 à 10:40

1 réponse

Meilleure réponse

Si vous obtenez l'écran vide, vous devez créer une mise en page

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
         android:layout_width="match_parent"
         android:layout_height="match_parent"
        android:text="ringing"
        android:textSize="100dp"/>
</LinearLayout>

Ouvrez votre ReminderNotifications, ajoutez cette mise en page par SetContentView(Resource.Layout.Alertlayout); dans la méthode OnCreate.

using Android.App;
using Android.Content;
using Newtonsoft.Json;
using reminderapp.Models;
using reminderapp.HelperRepository;
using Android.OS;

namespace reminderapp.Notifications
{
    //[BroadcastReceiver(Enabled = true)]
    [Activity(Label = "ReminderApp")]
    public class ReminderNotifications : Activity
    {
        Reminder reminder;
        public ReminderNotifications()
        {
        }
        string CHANNEL_ID = "dan1414";
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Alertlayout);

            var channel = new NotificationChannel(CHANNEL_ID, "FCMDD Notifications", NotificationImportance.Default)
            {
                Description = "Cloud Messages appear in this channel"
            };
        string date=    this.Intent.GetStringExtra("date");
         string time=   this.Intent.GetStringExtra("time");
            reminder = ReminderHelper.SelectReminderByDateAndTime(Application.Context, date, time);
            if (reminder != null)
            {
                Intent newIntent = new Intent(this, typeof(ReminderContent));
                newIntent.PutExtra("reminder", JsonConvert.SerializeObject(reminder));

                Android.Support.V4.App.TaskStackBuilder stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this);
                stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(ReminderContent)));
                stackBuilder.AddNextIntent(newIntent);

                PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

                Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                .SetAutoCancel(true)
                .SetContentIntent(resultPendingIntent)
                .SetContentTitle("Reminder!!")
                .SetSmallIcon(Resource.Drawable.Screenshot_2020_11_11_at_4_57_02_PM)
                .SetContentText("Click for details..");
                //.SetContentInfo("Start");
                NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(channel);
                notificationManager.Notify(0, builder.Build());
            }
        }

    
    }
}

Et je débogue votre code, j'ai trouvé que reminder = ReminderHelper.SelectReminder(Application.Context); ne peut pas obtenir les données de sqlite DB.

Donc, nous pourrions changer le mode de filtrage. Tout d'abord, veuillez ouvrir MainActivity.cs, trouvé la méthode ScheduleReminder. J'envoie date et time au ReminderNotifications.cs, nous pouvons obtenir le date et time dans le ReminderNotifications.cs, date et time nous aidera à exécuter la requête dans la base de données

 public void ScheduleReminder(Reminder reminder)
        {
            AlarmManager manager = (AlarmManager)GetSystemService(AlarmService);
            Intent myIntent;
            PendingIntent pendingIntent;
            myIntent = new Intent(this, typeof(ReminderNotifications));
            myIntent.PutExtra("date", reminder.Date);
            myIntent.PutExtra("time", reminder.Time);
            var t = reminder.Time.Split(':');
            var ampm = t[1].Split(' ')[1];
            var hrr = Convert.ToDouble(t[0]);
            var min = Convert.ToDouble(t[1].Split(' ')[0]);

            string dateString = Convert.ToString(reminder.Date + " " + hrr + ":" + min + ":00 " + ampm);

            DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dateString);
            var millisec = dateOffsetValue.ToUnixTimeMilliseconds();

            pendingIntent = PendingIntent.GetActivity(this, 0, myIntent, 0);
            manager.Set(AlarmType.RtcWakeup, millisec, pendingIntent);
        }

Donc, j'écris une nouvelle méthode dans le ReminderHelper.cs.

 public static Reminder SelectReminderByDateAndTime(Context context, string date, string time )
        {
            Reminder reminder;
            SQLiteDatabase db = new DataStore(context).WritableDatabase;
            string[] columns = new string[] { ColumnID, ColumnDate, ColumnTime, ColumnNote };
            using (ICursor cursor = db.Query(TableName, columns, ColumnDate + "=? AND " + ColumnTime + "=?", new string[] { date, time }, null, null, null))
            {
                if (cursor.MoveToNext())
                {
                    reminder = new Reminder
                    {
                        Id = cursor.GetInt(cursor.GetColumnIndexOrThrow(ColumnID)),
                        Date = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnDate)),
                        Time = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnTime)),
                        Note = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnNote))
                    };
                }
                else
                {
                    reminder = null;
                }
            }
            return reminder;

        }

Voici l'exécution de GIF.

enter image description here

2
Leon Lu - MSFT 17 nov. 2020 à 09:40