首页 文章

Xamarin.Forms:应用程序关闭时,广播接收器无法正常工作

提问于
浏览
4

我正在使用Xamarin.Forms处理一个应用程序,虽然大多数工作正常,但是当应用程序不在RAM中时,我找不到让我的广播接收器工作的方法 - 这意味着即使它“轻轻地” “由Android关闭,而不是由用户强制关闭它 .

当应用程序在前台运行或应用程序在后台时,广播接收器本身正常工作,但尚未被杀死 . 我已经花了几天时间寻找解决方案,而我却无法成功 . 我已经在Xamarin论坛上看到了一些提示,并在此处声明我的广播接收器在服务中,并在MainActivity文件中启动该服务,虽然看起来服务正在运行,但它仍然没有对我的本地通知做任何事情 .

据我所知,在Java Android开发中,您所要做的就是在清单文件中声明接收器并且它可以工作,但在使用Xamarin(非常棒的)技术时似乎并非如此 .

我希望你们中的一些人也面对这个问题并了解解决方案,因为我非常绝望 . 非常感谢您的时间,祝您度过愉快的一天!

EDIT:

Receiver是使用Xamarin的代码方式声明的,在生成的Manifest中它看起来像这样:

receiver android:name="md5d0a2bd06806e04fc29264ca7dfdf52f5.AlarmService"

这是BroadcastReceiver本身:

[BroadcastReceiver(Enabled=true)]
public class AlarmService : BroadcastReceiver, IAlarmService
{
    List<LocalNotification> notifications;
    public override void OnReceive (Context context, Intent intent)
    {
        PowerManager pm = (PowerManager) context.GetSystemService(Context.PowerService);
        PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.Partial, "");
        wl.Acquire();

        Intent resultIntent = new Intent(context, context.GetType());
        resultIntent.PutExtra ("Notification", true);

        IList<string> values = intent.GetStringArrayListExtra ("NotificationStrings");

        new LocalNotificationService(context).Notify (values [0], values [1], values [2], values[3]);
        wl.Release();       
    }

它收到的PendingIntent设置如下:

Intent intent = new Intent (context, typeof(AlarmService));
        intent.SetAction (notifications [requestCode].Id ?? Guid.NewGuid ().ToString ());
        intent.PutStringArrayListExtra ("NotificationStrings", new List<string>() {
            notifications [requestCode].Title,
            notifications [requestCode].Body,
            notifications [requestCode].AlertAction,
            notifications [requestCode].UserData,
            notifications [requestCode].Id
        });
AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);

        PendingIntent pi = PendingIntent.GetBroadcast(context, 0, intent, 0);

        am.Set (AlarmType.RtcWakeup, (long)(Java.Lang.JavaSystem.CurrentTimeMillis () + (dateTime.Value.ToUniversalTime () - DateTime.Now.ToUniversalTime ()).TotalMilliseconds), pi);

然而,即使我删除了OnReceive中的代码,而不是没有发生任何事情,我得到系统消息,指出应用程序已经停止工作,这让我觉得上下文或Intent一定有问题 - 当app活动进入时一切正常RAM .

2 回答

  • 1

    您需要在应用清单中添加在后台运行的权限 . 看看我的工作解决方案here

  • 0

    事实证明,我是一个完全白痴;问题不在接收器或警报设置器中 . 我在LocalNotificationService中处理了错误的Context . 我使用Forms.Context进行时间而不是接收器传递的Context .

    伙计们,浪费你的时间对不起 . 感谢帮助!

相关问题