使用 xamarin 表单中的闹钟管理器为 android 安排通知 [英] Schedule notification using alarm manager in xamarin forms for android

查看:59
本文介绍了使用 xamarin 表单中的闹钟管理器为 android 安排通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我创建了一个依赖项来显示通知

  • I have created a dependencie to show the notifications

在我的 DeviceDetails_Droid.cs 中,我设置了 30 秒的闹钟

In My DeviceDetails_Droid.cs I've set set alarm for 30 seconds

本地通知功能在应用程序运行时完美运行活动但是当我杀死应用程序(关闭应用程序)时,警报接收器没有接到电话.

The functionality for local notification works perfectly when app is active but when I killed the app (close app) the alarm receiver not getting called.

public void ShowNotification(string message, string title)
{

Intent alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
alarmIntent.PutExtra ("message", message);
alarmIntent.PutExtra ("title", title);

    PendingIntent pendingIntent = PendingIntent.GetBroadcast(Forms.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
    AlarmManager alarmManager = (AlarmManager) Forms.Context.GetSystemService(Context.AlarmService);

    //TODO: For demo set after 5 seconds.
    alarmManager.Set(AlarmType.RtcWakeup, DateTime.Now.Millisecond + 30000, pendingIntent);
}

<小时>

  • 在 Android 的 MainActivity 中
  • [BroadcastReceiver]
    public class AlarmReceiver : BroadcastReceiver
    {
        public override void OnReceive (Context context, Intent intent)
        {
    
            var message = intent.GetStringExtra ("message");
            var title = intent.GetStringExtra ("title");
    
            var notIntent = new Intent (context, typeof(MainActivity));
            var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
            var manager = NotificationManagerCompat.From (context);
    
            var style = new NotificationCompat.BigTextStyle();
            style.BigText(message);
    
    
    
            //Generate a notification with just short text and small icon
            var builder = new NotificationCompat.Builder (context)
                .SetContentIntent (contentIntent)
                .SetSmallIcon (Resource.Drawable.Icon)
                .SetContentTitle (title)
                .SetContentText (message)
                .SetStyle (style)
                .SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis ())
                .SetAutoCancel (true);
    
            var notification = builder.Build();
            manager.Notify(0, notification);
        }
    }
    

    <小时>

    • 在清单文件中
    • <receiver 
       android:name=".AlarmReceiver" 
       android:enabled="true" 
       android:exported="true" 
       android:process=":remote" 
       android:label="AlarmReceiver">
      

      <小时>

      • 上面的代码在app处于running状态时完美运行但是当应用程序关闭或终止时通知不起作用
      • 推荐答案

        1) 如果有人杀死了您的应用程序,注册到您应用程序的警报将被取消.

        1) If someone kills your app, alarms registered to your app are cancelled.

        2) 您可以在设备的 Boot 后台启动您的服务以注册您的闹钟,或运行您需要设置通知的任何其他代码...

        2) You can start your service in the background on Boot of the device in order to register your alarms, or run any other code you need to setup your notifications...

        • 将android.intent.action.BOOT_COMPLETED"添加到您的广播接收器:
        [BroadcastReceiver]
        [IntentFilter(new string[]{"android.intent.action.BOOT_COMPLETED"}, Priority = (int)IntentFilterPriority.LowPriority)]
        public class AlarmReceiver : BroadcastReceiver
        

        <小时>

        • 在您的清单中添加启动完成权限:
        • <uses-permission android:name="android.permission.WAKE_LOCK"/>
          <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
          <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>    
          

          <小时>

          对于 Xamarin 的股票价格示例,如果您设置RECEIVE_BOOT_COMPLETED",您将自动"重启您的服务,您将在手机重启后开始接收通知,而无需先启动您的应用:


          In the case of Xamarin's Stock Price example, if you set "RECEIVE_BOOT_COMPLETED" you are "auto" restart your service and the your will start receiving notifications upon reboot of their phone without first launching your app:

          [BroadcastReceiver]
          [IntentFilter(new string[]{StockService.StocksUpdatedAction,Boo "android.intent.action.BOOT_COMPLETED"}, Priority = (int)IntentFilterPriority.LowPriority)]
          public class StockNotificationReceiver : BroadcastReceiver
          

          3) 您可以使用 ServiceSeviceIntent 并覆盖 StartCommandResult 以返回 Sticky

          3) You can use a Service vs. a SeviceIntent and override the StartCommandResult to return Sticky

          对于基于粘性的服务,如果它被终止,它会重新启动.

          With a Sticky-based Service, it is restarted if it gets terminated.

          从 onStartCommand(Intent, int, int) 返回的常量:如果这个服务的进程在它启动时被杀死(从 onStartCommand(Intent, int, int) 返回后),那么让它保持在启动状态,但不要't 保留这个传递的意图.稍后系统将尝试重新创建该服务.因为处于启动状态,所以会保证在创建新的服务实例后调用onStartCommand(Intent, int, int);如果没有任何挂起的启动命令要传递给服务,它将使用空意图对象调用,因此您必须注意检查这一点.

          Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

              public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
              {
                  return StartCommandResult.Sticky;
              }
          

          这篇关于使用 xamarin 表单中的闹钟管理器为 android 安排通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆