Xamarin广播接收器无法接收

时间:2016-09-15 05:00:48

标签: android xamarin xamarin.android android-broadcast

我有一个不接收任何广播的BroadcastReceiver。

[BroadcastReceiver]
[IntentFilter(new[] { _broadcastId })]
public class CallBroadcaster : BroadcastReceiver, IAcceptCallService
{
   const string _broadcastId = "headExtension.droid.services.AcceptIndividualCall";

   public CallBroadcaster ()
   { 
   }

   Activity CurrentActivity
   {
      get { return Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity; }
   }

   public void Send()
   {
      var intent = new Intent(_broadcastId);
      intent.PutExtra(Intent.ExtraText, "Accept");
      intent.SetType("text/plain");

      CurrentActivity.SendBroadcast(intent);
   }

   public override void OnReceive(Context context, Intent intent)
   {
      Console.WriteLine("Received");
   }
}

OnReceive方法永远不会被命中。如何在xamarin中正确实现广播接收器。

这里只有一个项目,所以这不是关于从另一个项目接收意图的问题的重复。

1 个答案:

答案 0 :(得分:0)

我得到了它的工作: 问题出在数据类型上。意图以“text / plain”发送,而IntentFilter用于接收不匹配。

解决方案是将DataMimeType =“text / plain”添加到intent过滤器,如下所示:

[BroadcastReceiver]
[IntentFilter(new[] { _broadcastId }, DataMimeType="text/plain")]
public class CallBroadcaster : BroadcastReceiver, IAcceptCallService
{
   const string _broadcastId =     "headExtension.droid.services.AcceptIndividualCall";

   public CallBroadcaster ()
   { 
   }

   Activity CurrentActivity
   {
      get { return Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity; }
   }

   public void Send()
   {
      var intent = new Intent(_broadcastId);
      intent.PutExtra(Intent.ExtraText, "Accept");
      intent.SetType("text/plain");

      CurrentActivity.SendBroadcast(intent);
   }

   public override void OnReceive(Context context, Intent intent)
   {
      Console.WriteLine("Received");
   }
}