我应该将BroadcastReciver或Service与警报管理器一起使用吗?

时间:2019-01-01 08:38:40

标签: android android-intent

我应该通过广播接收器调用我的服务还是应该使用警报管理器直接调用它。目前,我正在直接使用服务,但有时未触发警报。

PendingIntent pendingIntent = PendingIntent.getService(getContext().getApplicationContext(), 1, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); 

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent); 

3 个答案:

答案 0 :(得分:0)

BroadcastReceiver不适用于任何类型的长时间运行的操作(无论是同步还是异步等待某些回调)。它仅用于接收某些事件(广播),然后将所有长时间运行的操作移交给相应的组件(即“活动”或“服务”)。

IntentService用于在另一个线程上处理的长时间运行的同步操作。 (前景)服务允许您或多或少地充当不可见的活动。您可以等待异步回调(即用户关闭警报)。

您可以使用我制作的这个库。 service in background and foreground与您一起运行服务,然后接收带有广播的呼叫

使用简单的代码,您可以像这样开始呼叫或启动服务

RunService service = new RunService(this);
service.call(5);

并在此方法内执行操作

  BroadcastReceiver alarm_receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // your logic here
            Log.i("alarm_received", "success");

        }
    };

别忘了注册该服务,并在销毁该服务时将其删除,就像在文档中看到的一样。

答案 1 :(得分:0)

我建议使用广播接收器,并且当onReceive可以启动服务或执行任何操作时,这也很有用,尤其是当您需要接收android.intent.action.BOOT_COMPLETED重新安排未决警报时,因为设备重新启动时,操作系统将删除所有待处理的警报,有关更多信息,请检查此link

答案 2 :(得分:-1)

namespace Diabetes.Droid

{     [应用]     公共类MainApplication:应用程序     {         ISetAlarm alarmService;         公共静态上下文AppContext;

    public MainApplication()
    {

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


    public override void OnCreate()
    {

        base.OnCreate();
        AppContext = this.ApplicationContext;
        alarmService = new SetAlarmImplementation();
        alarmService.SetAlarm(13,58,"hello","great work ");
    }



    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, new Intent(AppContext, typeof(AppStickyService)), 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);

    }





    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);
            Toast.MakeText(this, "Service started", ToastLength.Long).Show();
            //alarm.Cancel(pintent);
        }
    }

    public static void StopService()
    {
        AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
        {
            // Toast.MakeText(this,"Service started", ToastLength.Long).Show();

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

这是AlarmImplementation.class

public class SetAlarmImplementation : ISetAlarm
{

    public SetAlarmImplementation(){}


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


        Intent myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
        myintent.PutExtra("message", message);
        myintent.PutExtra("title", title);
        PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);

        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, pendingintent);
    }
}
This is BroadcastReceiver.class
[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);

    }
}

这是最终的服务课程

[Service]
public class AppStickyService : Service
{

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

       // Toast.MakeText(this, "Service started Habiibi", ToastLength.Long).Show();
        //WireAlarm();
        System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
    }

    public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
    {
        SetAlarm(12,39,"Try","Start Service");

        return StartCommandResult.Sticky;
    }

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

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