当应用未运行时,如何使广播接收器正常工作?

问题描述 投票:1回答:1

我正在尝试创建一个应用程序,当该应用程序未运行时,我需要在其中发送用户通知。我正在用一个广播接收器来完成它,当日期改变时它就开始工作。意思是当日期更改时,广播接收者使用处理程序来发送通知。当应用程序运行时,它可以正常运行,但是当应用程序未运行时,广播接收器不起作用,并且不发送通知。

这里是代码:

我首先在清单中:

<receiver android:name=".MyBroadcastRecieverDate" >
    <intent-filter>
      <action android:name="android.intent.action.DATE_CHANGED" />
    </intent-filter>
  </receiver>

在主要活动中,我建立并注册广播接收者:

this.recieverDate = new MyBroadcastRecieverDate();

protected override void OnResume()
        {
            base.OnResume();
            RegisterReceiver(recieverDate, new IntentFilter(Intent.ActionDateChanged));
        }

这是接收者的类别:

[BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Intent.ActionDateChanged })]
    class MyBroadcastRecieverDate : BroadcastReceiver
    {
        MyHandler handler;

        public MyBroadcastRecieverDate()
        {
        }

        public override void OnReceive(Context context, Intent intent)
        {
            if(intent.Action.Equals(Intent.ActionDateChanged))
            {
                handler = new MyHandler(context);
                Message msg = new Message();
                msg.Obj = "";
                msg.Arg1=1;
                handler.SendMessage(msg);
            }
        }
    }

[如果有人可以帮助我,告诉我即使在应用未运行时如何使接收器正常工作,也将对我有很大帮助。谢谢。

c# xamarin broadcastreceiver
1个回答
0
投票

在Android 8.0之前,我们可以使用Service在后台/关闭状态下激活应用程序,请选中此answer

但是,Android从8.0开始限制后台执行,Android应用程序不再具有在后台自由运行的功能,为了执行后台工作,有几种服务可供选择,我建议您看看Foreground Services


参考Background Execution Limits in Android 8.0

© www.soinside.com 2019 - 2024. All rights reserved.