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

C# Android: Get Broadcast Receiver on a service?

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

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

Service 嵌入 BroadcastReceiver 示例:

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

    public WhosebugService()
    {
        broadcastReceiver = new WhosebugServiceBroadcastReceiver(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 WhosebugServiceBinder(this);
        return binder;
    }

    [IntentFilter(new[] { BROADCASTFILTER })]
    class WhosebugServiceBroadcastReceiver : BroadcastReceiver
    {
        WhosebugService service;
        public WhosebugServiceBroadcastReceiver(WhosebugService 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 WhosebugServiceBinder : Binder
{
    readonly WhosebugService service;

    public WhosebugServiceBinder(WhosebugService service)
    {
        this.service = service;
    }

    public WhosebugService GetWhosebugService()
    {
        return service;
    }
}

用法:

var intentForService = new Intent(WhosebugService.BROADCASTFILTER)
    .PutExtra("Stack", "Overflow");
Application.Context.SendBroadcast(intentForService);