How can i call a BroadCastReceiver inside a Servic

2019-03-06 01:42发布

问题:

Am working on an Alarm Application which works on a scheduled time , and i want it to work when the Users have launched the App or not (Both).

Meaning the Application will notify like Usual Alarms

Now i came to the point when i wanted to call a broadcastReceiver inside a Service so that , it performs that action.

What i noticed :

1.When i use a Broadcast , the Alarm Notification comes only when i have opened the App. 2.When i use a Service the Alarm comes only when am outside the Application(When it's not launched), (Here i place my code in the OnStartCommand()).

So i came to a conclusion of adding both of them to make a Scheduled notification when the App is both opened or closed. But i don't know how

Now The source codes are below.

Below is my Service.

namespace Diabetes.Droid.Resources
{
    [Service]
    public class AppStickyService : Service
    {

        public override void OnCreate()
        {
            base.OnCreate();


            System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
        }

        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {



            return StartCommandResult.Sticky;
        }

        public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
        {
            System.Diagnostics.Debug.WriteLine("Sticky Service - Binded");

            return null;
        }

        public override void OnDestroy()
        {
            System.Diagnostics.Debug.WriteLine("Sticky Service - Destroyed");
            base.OnDestroy();
        }
    }
}

my BroadCast

namespace Diabetes.Droid
{
    [BroadcastReceiver]
    [IntentFilter(new string[] { "android.intent.action.BOOT_COMPLETED" }, Priority = (int)IntentFilterPriority.LowPriority)]
    public class AlarmReceiver : BroadcastReceiver
    {

        public override void OnReceive(Context context, Intent intent)
        {

            var message = intent.GetStringExtra("message");
            var title = intent.GetStringExtra("title");

            //Show toast here
            //Toast.MakeText(context, "Hello it's me ", ToastLength.Short).Show();
            var extras = intent.Extras;

            if (extras != null && !extras.IsEmpty)
            {
                NotificationManager manager_ = context.GetSystemService(Context.NotificationService) as NotificationManager;
                var notificationId = extras.GetInt("NotificationIdKey", -1);
                if (notificationId != -1)
                {
                    manager_.Cancel(notificationId);
                }
            }

            //Create intent for action 1 (TAKE)
            var actionIntent1 = new Intent();
            actionIntent1.SetAction("ARCHIVE");
            var pIntent1 = PendingIntent.GetBroadcast(context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);

            //Create intent for action 2 (REPLY)
            var actionIntent2 = new Intent();
            actionIntent2.SetAction("REPLY");
            var pIntent2 = PendingIntent.GetBroadcast(context, 0, actionIntent2, PendingIntentFlags.CancelCurrent);

            Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

            var contentIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.CancelCurrent);

            var pending = PendingIntent.GetActivity(context, 0,
                resultIntent,
                PendingIntentFlags.CancelCurrent);
            //seting an alarm
            MedicationDatabase db = new MedicationDatabase();
            var alarm_list = db.GetAlarmList();
            //Debug.WriteLine(" Time -- : "+ m.ToString());


            // Instantiate the Big Text style:
            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();


            var builder =
                new Notification.Builder(context)
                                .AddAction(Resource.Drawable.tick_notify, "ARCHIVE", pIntent1)
                                .AddAction(Resource.Drawable.cancel_notify, "REPLY", pIntent2)
                                .SetSmallIcon(Resource.Drawable.ic_launcher)
                                .SetContentTitle("Diabetics Reminder")
                                .SetDefaults(NotificationDefaults.Sound)
                                .SetStyle(new Notification
                                .BigTextStyle()
                                .SetSummaryText("")
                                .SetBigContentTitle(title)
                                .BigText(message)
             ).SetDefaults(NotificationDefaults.All);

            builder.SetContentIntent(pending);

            var notification = builder.Build();


            var manager = NotificationManager.FromContext(context);
            manager.Notify(10010, notification);

        }
    }

    [BroadcastReceiver]
    [IntentFilter(new string[] { "ARCHIVE", "REPLY" })]
    public class CustomActionReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {

            switch (intent.Action)
            {
                case "ARCHIVE":
                    try
                    {
                        MedicationDatabase db = new MedicationDatabase();
                        db.addtracktaken("true");
                        Toast.MakeText(context, "DOSAGE TAKEN", ToastLength.Short).Show();
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.StackTrace);
                    }
                    break;
                case "REPLY":
                    try
                    {
                        Toast.MakeText(context, "ARCHIVE", ToastLength.Short).Show();
                        MedicationDatabase db = new MedicationDatabase();
                        db.addtrackmissed("true");
                        Toast.MakeText(context, "DOSAGE MISSED", ToastLength.Short).Show();
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.StackTrace);
                    }
                    break;
            }

            var extras = intent.Extras;

            if (extras != null && !extras.IsEmpty)
            {
                NotificationManager manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
                var notificationId = extras.GetInt("NotificationIdKey", -1);
                if (notificationId != -1)
                {
                    manager.Cancel(notificationId);
                }
            }
        }
    }
}

MainApplication class

This class is the one which initializes the Alarm to start working.

namespace Diabetes.Droid
{
    [Application]
    public class MainApplication : Application
    {
        ISetAlarm alarmService;
        public static Context AppContext;

        public MainApplication()
        {

        }
        public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
        {
        }


        public override void OnCreate()
        {

            base.OnCreate();
            AppContext = this.ApplicationContext;

          SetAlarm(12, 22, title, message);
        }




        public void SetAlarm(int hour, int minute, string title, string message)
        {

                        AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
                        Intent myintent = new Intent(Android.App.Application.Context, typeof(AppStickyService));
                        myintent.PutExtra("message", message);
                        myintent.PutExtra("title", title);
                        //PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
                        PendingIntent pintent = PendingIntent.GetService(AppContext, 0, myintent, 0);

                        Java.Util.Date date = new Java.Util.Date();
                        Java.Util.Calendar cal = Java.Util.Calendar.Instance;
                        cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
                        cal.Set(Java.Util.CalendarField.HourOfDay, hour);
                        cal.Set(Java.Util.CalendarField.Minute, minute);
                        cal.Set(Java.Util.CalendarField.Second, 0);
                        AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
                        alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pintent);
                        alarmManager.Cancel(pintent);

        }



        private Boolean isMyServiceRunning()
        {
            ActivityManager man_ = (ActivityManager)Android.App.Application.Context.GetSystemService(Context.ActivityService);

            foreach (Android.App.ActivityManager.RunningServiceInfo service in man_.GetRunningServices(int.MaxValue))
            {
                if (typeof(AppStickyService).Name.Equals(service.Service.ClassName))
                {
                    return true;
                }
            }
            return false;
        }

        public void StartService()
        {

            AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
            {

                PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
                AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
                //alarm.Cancel(pintent);
            }
        }

        public static void StopService()
        {
            AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
            {
                PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
                AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
                alarm.Cancel(pintent);
            }
        }
    }
}

Now how can i perfect my Local Notification to be like the usual Alarms in android mobile devices