C#Android:在服务上获取广播接收器?

我正在xamarin.android中开发辅助功能服务.
一切都很好,但我想在服务上使用广播接收器.
我知道我必须从广播接收器派生我的可访问性服务,但这是不可能的,因为该服务已经从Android.AccessibilityService派生了.
实际上,事实是,当用户在主要活动上进行一些配置更改时,我想提出一个广播接收器,我的可访问性服务应为此监听.
那么,对此有什么想法吗?

解决方法:

在您的Service中,定义一个BroadcastReceiver内部类,并在Service构造函数中创建并注册BroadcastReceiver.

带有嵌入式BroadcastReceiver示例的服务:

[Service(Label = "*Service")]
[IntentFilter(new String[] { "com.yourpackage.*Service" })]
public class *Service : Service
{
    public const string BROADCASTFILTER = "com.yourpackage.intent.action.IMAGEOPTIMIZER";
    IBinder binder;
    *ServiceBroadcastReceiver broadcastReceiver;

    public *Service()
    {
        broadcastReceiver = new *ServiceBroadcastReceiver(this);
        RegisterReceiver(broadcastReceiver, new IntentFilter(BROADCASTFILTER));
    }

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

    public override IBinder OnBind(Intent intent)
    {
        binder = new *ServiceBinder(this);
        return binder;
    }

    [IntentFilter(new[] { BROADCASTFILTER })]
    class *ServiceBroadcastReceiver : BroadcastReceiver
    {
        *Service service;
        public *ServiceBroadcastReceiver(*Service service) : base()
        {
            this.service = service;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            var stack = intent.GetStringExtra("Stack");
            Log.Debug("SO", $"{BROADCASTFILTER} Received : {stack}");
            // access your service via the "service" var...
        }
    }
}

public class *ServiceBinder : Binder
{
    readonly *Service service;

    public *ServiceBinder(*Service service)
    {
        this.service = service;
    }

    public *Service Get*Service()
    {
        return service;
    }
}

用法:

var intentForService = new Intent(*Service.BROADCASTFILTER)
    .PutExtra("Stack", "Overflow");
Application.Context.SendBroadcast(intentForService);
上一篇:C#-使用Xamarin.Android为Parse.com服务器制作更漂亮的Facebook登录屏幕


下一篇:使用Jquery解析xml的两种方法