AlarmManager计划任务每​​周运行一次

时间:2018-02-01 12:42:11

标签: xamarin xamarin.forms xamarin.android

我想安排一个Sql server任务(存储过程)在我的应用程序的后台运行,该任务从星期二开始每小时运行一次,直到任务返回数据,然后向用户发送通知,任务应该停止,直到下周二,然后在下周二,任务应该重新开始。

使用我已实现的代码,在第一个警报更新后,应用程序始终在AlarmReceiver类的OnReceive内循环。

MainActivity:

    [Activity(Label = "Portal", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
    WindowSoftInputMode = SoftInput.AdjustResize)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{   protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(bundle);
        SecureStorageImplementation.StoragePassword = "1234**";
        AsNumAssemblyHelper.HoldAssembly();
        global::Xamarin.Forms.Forms.Init(this, bundle);
        ImageCircleRenderer.Init();
        try
        {
            if (Settings.AccessAlarm == 0)
            {
                Intent alarmIntent = new Intent(this, typeof(AlarmReceiver));
                alarmIntent.SetClass(this, typeof(AlarmReceiver));
                PendingIntent pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
                AlarmManager alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
                alarmManager.SetRepeating(AlarmType.RtcWakeup, 1000, BootReceiver.reminderInterval, pending);
                PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent, 0);
                Settings.AccessAlarm = 1;
            }
        }
        catch (Exception e)
        {
            Settings.AccessAlarm = 0;
        }
        LoadApplication(new App());

        if (Settings.AlarmNotification == 1 && Settings.LoginSucess && Intent.GetStringExtra("AcessKeyIntent") == "123")
        {
            Settings.Semana = "Next";
            Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new EmentaTabbedPage());
        }

        Settings.AlarmNotification = 0;
    }

}

BootReceiver:

 [BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootReceiver : BroadcastReceiver
{
    //the interval currently every one minute
    //to set it to dayly change the value to 24 * 60 * 60 * 1000
    public static long reminderInterval = AlarmManager.IntervalHour;
    //public static long reminderInterval = 3 * 1000;

    public static long FirstReminder()
    {
        System.Random rnd = new System.Random();

        int minutenumber = rnd.Next(20, 40);


        Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
        calendar.Set(Java.Util.CalendarField.DayOfWeek, Calendar.Tuesday);
        calendar.Set(Java.Util.CalendarField.HourOfDay, 15);
        calendar.Set(Java.Util.CalendarField.Minute, 20);
        return calendar.TimeInMillis;

    }


    public override void OnReceive(Context context, Intent intent)
    {
        try
        {
            Console.WriteLine("BootReceiver: OnReceive");
            var alarmIntent = new Intent(context, typeof(AlarmReceiver));
            var pending = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
            AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
            alarmManager.SetRepeating(AlarmType.RtcWakeup, FirstReminder(), reminderInterval, pending);
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, alarmIntent, 0);
            Settings.AccessAlarm = 1;
        }
        catch (Exception e)
        {
            Settings.AccessAlarm = 0;
        }

    }
}

AlarmReceiver:

  [BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
    private int z = 0;
    private int i;
    private bool EmentaSequinteTest;

    public void MethodTabs()
    {
        try
        {
            EmentaSequinteTest = false;
            if (Settings.Username != "")
            {
                string query = "Mobileapp";
                DbFetcherCheck a = new DbFetcherCheck();
                EmentaSequinteTest
                    = a.Ementas(query, Settings.Username, "Next");
            }
        }
        catch (Exception e)
        {
            if (z < 2)
            {
                if (Settings.Ip == "192.168.1.99")
                {
                    z++;
                    Settings.Ip = "192.122.72.69";
                    MethodTabs();
                }
                else
                {
                    z++;
                    Settings.Ip = "192.168.1.99";
                    MethodTabs();
                }
            }
            else
            {
                z--;
            }
        }

    }

    public override void OnReceive(Context context, Intent intent)
    {
        try
        {
            MethodTabs();
            if (EmentaSequinteTest)
            {
                Settings.AlarmNotification = 1;



                //Stops/updates Alarm


                    Intent alarmIntent = new Intent(context, typeof(AlarmReceiver));
                    alarmIntent.SetClass(context, typeof(AlarmReceiver));
                    PendingIntent pending = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.CancelCurrent);
                    AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
                    alarmManager.SetInexactRepeating(AlarmType.RtcWakeup,BootReceiver.FirstReminder(), 1 * 60 * 60 * 1000, pending);




                var title = "Menu";
                var message = "Menu is Available";


                //The activity opened when we click the notification is SecondActivity

                var resultIntent = new Intent(context, typeof(MainActivity));

                resultIntent.PutExtra("AcessKeyIntent", "123");

                var deleteIntent = new Intent(context, typeof(NotificationBroadcastReceiver));
                deleteIntent.SetAction("Action");

                // TODO: Set extras as needed.

                var deletePendingIntent = PendingIntent.GetBroadcast(context, 0, deleteIntent, PendingIntentFlags.CancelCurrent);

                PendingIntent pending1 = PendingIntent.GetActivities(context, 0,
                    new Intent[] { resultIntent },
                    PendingIntentFlags.OneShot);


                using (var notificationManager = NotificationManager.FromContext(context))
                {
                    Notification notification;
                    if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O)
                    {
                        notification = new Notification.Builder(context)
                                                    .SetContentTitle(title)
                                                    .SetContentText(message)
                                                    .SetAutoCancel(true)
                                                    .SetSmallIcon(Resource.Drawable.icon)
                                                    .SetDefaults(NotificationDefaults.All)
                                                    .SetDeleteIntent(deletePendingIntent)
                                                    .SetContentIntent(pending1)
                                                    .Build();
                    }
                    else
                    {

                        var myUrgentChannel = context.PackageName;
                        const string channelName = " App";

                        NotificationChannel channel;
                        channel = notificationManager.GetNotificationChannel(myUrgentChannel);
                        if (channel == null)
                        {
                            channel = new NotificationChannel(myUrgentChannel, channelName, NotificationImportance.High);
                            channel.EnableVibration(true);
                            channel.EnableLights(true);
                            channel.SetSound(
                                RingtoneManager.GetDefaultUri(RingtoneType.Notification),
                                new AudioAttributes.Builder().SetUsage(AudioUsageKind.Notification).Build()
                            );
                            channel.LockscreenVisibility = NotificationVisibility.Public;
                            notificationManager.CreateNotificationChannel(channel);
                        }
                        channel?.Dispose();

                        notification = new Notification.Builder(context)
                                                    .SetChannelId(myUrgentChannel)
                                                    .SetContentTitle(title)
                                                    .SetContentText(message)
                                                    .SetAutoCancel(true)
                                                    .SetDeleteIntent(deletePendingIntent)
                                                    .SetSmallIcon(Resource.Drawable.icon_notif)
                                                    .SetContentIntent(pending1)
                                                    .Build();
                    }

                    notificationManager.Notify(1331, notification);
                    notification.Dispose();
                }
            }
        }
        catch (Exception)
        {

        }
    }
}

NotificationBroadcastReceiver:

 [BroadcastReceiver]
public class NotificationBroadcastReceiver:BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action == "Action")
        {
            Settings.AlarmNotification = 0;
        }
    }
}

0 个答案:

没有答案