Android 设备重启后重复通知丢失 Xamarin Forms App C#

Repeating Notifications Lost After Android Device Reboot Xamarin Forms App C#

我正在使用 C# 开发 Xamarin Forms 应用程序。我按照本教程设置了重复的本地通知: https://www.c-sharpcorner.com/article/how-to-send-local-notification-with-repeat-interval-in-xamarin-forms/

在大多数情况下,关于通知触发的一切都正常。但是,如果我重新启动设备,我将不再收到任何通知。

这是我的广播接收器class:

[BroadcastReceiver(Enabled = true, Label = "Local Notifications Broadcast Receiver")]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class ScheduledAlarmHandler : BroadcastReceiver
{
    public const string LocalNotificationKey = "LocalNotification";
    NotificationManager manager;
    const string channelId = "default";
    const string channelName = "Default";
    const string channelDescription = "The default channel for notifications.";

    public const string TitleKey = "title";
    public const string MessageKey = "message";

    bool channelInitialized = false;

    public override void OnReceive(Context context, Intent intent)
    {
        if (!channelInitialized)
        {
            CreateNotificationChannel();
        }

        ComponentName receiver = new ComponentName(AndroidApp.Context, Class.FromType(typeof(ScheduledAlarmHandler)).Name);
        PackageManager pm = AndroidApp.Context.PackageManager;
        pm.SetComponentEnabledSetting(receiver, ComponentEnabledState.Enabled, ComponentEnableOption.DontKillApp);

        var extra = intent.GetStringExtra(LocalNotificationKey);
        var notification = DeserializeNotification(extra);

        // Generating notification    
        var builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
            .SetContentTitle(notification.Title)
            .SetContentText(notification.Body)
            .SetSmallIcon(notification.IconId)
            .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
            .SetAutoCancel(true);

        var resultIntent = AndroidNotificationManager.GetLauncherActivity();
        resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
        var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(AndroidApp.Context);
        stackBuilder.AddNextIntent(resultIntent);

        Random random = new Random();
        int randomNumber = random.Next(9999 - 1000) + 1000;

        var resultPendingIntent =
            stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.CancelCurrent);
        builder.SetContentIntent(resultPendingIntent);

        // Sending notification    
        var notificationManager = NotificationManagerCompat.From(AndroidApp.Context);
        var notificationToNotify = builder.Build();
        notificationManager.Notify(randomNumber, notificationToNotify);
    }

    private LocalNotification DeserializeNotification(string notificationString)
    {

        var xmlSerializer = new XmlSerializer(typeof(LocalNotification));
        using (var stringReader = new StringReader(notificationString))
        {
            var notification = (LocalNotification)xmlSerializer.Deserialize(stringReader);
            return notification;
        }
    }

    void CreateNotificationChannel()
    {
        manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            var channelNameJava = new Java.Lang.String(channelName);
            var channel = new NotificationChannel(channelId, channelNameJava, NotificationImportance.Default)
            {
                Description = channelDescription
            };

            manager.CreateNotificationChannel(channel);
        }

        channelInitialized = true;
    }
}

本教程没有将 IntentFilter 属性添加到 class 或更新清单文件,但我稍后在搜索解决方案时添加了这些。

这是我的 AndroidManifest 文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.service_buddy">
  <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
  <application android:label="Service_Buddy.Android"></application>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
  <application>
    <receiver android:name="ServiceBuddy.Droid.ScheduledAlarmHandler" android:enabled="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
      </intent-filter>
    </receiver>
  </application>
</manifest>```


据我所知,重启后没有内存,就没了,所以无事可做。

不要浪费你的时间,就用 Shiny 吧,它是 xamarin 后台和前台服务领域真正的问题解决者。 shiny getting started