即使我添加了事件处理程序,Xamarin自定义的BroadcastReceiver事件也始终为null

时间:2018-10-29 15:33:19

标签: c# android xamarin

我正在使用Xamarin创建一个Android应用。基本上,应用程序会检测传入的SMS,如果发件人是特定号码,则GUI会更新。我创建了一个类,该类继承了BroadcastReceiver并在适当的条件下引发该事件,但是即使我订阅了一种方法,该方法在按钮单击事件中被怀疑时也可以正常工作(我在MainActivity中创建了该类的实例)并在OnCreate方法中添加EventHandler)研究之后,代码EventHandler为null似乎有点奇怪……我在做什么错? 预先感谢!

BroadcastReceiver

[BroadcastReceiver(Exported = true, Enabled = true)]

[IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED"}, Priority =(int)IntentFilterPriority.HighPriority)]

public class NewSMSReceived : BroadcastReceiver
{
    public event EventHandler SMSArrived;

    public override void OnReceive(Context context, Intent intent)
    {
        if (Android.Provider.Telephony.Sms.Intents.SmsReceivedAction.Equals(intent.Action))
        {

            var info_Intent = intent.Extras;

            if (info_Intent != null)
            {
                Java.Lang.Object[] pdus = (Java.Lang.Object[]) info_Intent.Get("pdus");

                var msg = SmsMessage.CreateFromPdu((byte[]) pdus[0]);

                var msg_from = msg.DisplayOriginatingAddress;

                if (msg_from == "xxxxxxxxxx")
                {

                    Toast.MakeText(Application.Context, "New message from Weather Station", ToastLength.Short).Show();

                    SMSArrived?.Invoke(this, EventArgs.Empty);
                }
            }
        }
    }
}

主要活动代码

public class MainActivity : AppCompatActivity
{
    private NewSMSReceived SMSNotificator = new NewSMSReceived();

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.activity_main);

        this.SMSNotificator.SMSArrived += new EventHandler(this.showNewData);
    }

    private void showNewData(object sender, EventArgs e)
    {
        //
    }
}

1 个答案:

答案 0 :(得分:0)

我使用问题Xamarin Android : Change UI TextView text from Service or Receiver的答案使其起作用,@ SushiHangover的评论帮助我意识到了这个问题。使用OnResume方法注册NewSMSReceived实例,并使用OnPause方法注销它解决了该问题(在第一次尝试中,我没有删除NewSMSReceived的IntentFilter属性,但是它没有起作用)。代码修改如下:

GetEnumerator

MainActivity中的代码(实例仅初始化一次,并且事件通过“ OnCreate”方法进行了订阅)

MoveNext