C# Android: Get Broadcast Receiver on a service?

百般思念 提交于 2019-12-09 01:33:16

问题


I'm developing an accessibility service in xamarin.android. all is fine, but I want the broadcast receiver on the service. I know that I'll have to derive my accessibility service from broadcast receiver, but it's not possible because the service is already derived from Android.AccessibilityService. actually, the thing is that, when user does some configuration change on main activity, I want to raise an broadcast receiver for which, my accessibility service should listen. So, any ideas for this?


回答1:


Within your Service, define an BroadcastReceiver inner class and within your Service constructor create and register the BroadcastReceiver.

Service with embedded BroadcastReceiver Example:

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

    public StackOverflowService()
    {
        broadcastReceiver = new StackOverflowServiceBroadcastReceiver(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 StackOverflowServiceBinder(this);
        return binder;
    }

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

    public StackOverflowServiceBinder(StackOverflowService service)
    {
        this.service = service;
    }

    public StackOverflowService GetStackOverflowService()
    {
        return service;
    }
}

Usage:

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


来源:https://stackoverflow.com/questions/41924587/c-sharp-android-get-broadcast-receiver-on-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!