Skip to content Skip to sidebar Skip to footer

C# Android: Get Broadcast Receiver On A Service?

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

Solution 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);

Post a Comment for "C# Android: Get Broadcast Receiver On A Service?"