C# 安卓 : Get Broadcast Receiver on a service?

标签 c# android xamarin xamarin.android broadcast

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

最佳答案

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

Service 嵌入 BroadcastReceiver 示例:

[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;
    }
}

用法:

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

关于C# 安卓 : Get Broadcast Receiver on a service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924587/

相关文章:

C# SQL : update with params - getting 0 and without the text

c# - 根据用户数据重定向到 url

c# - 使用特定字符串从 List<string> 中删除所有内容

c# - 如何查找所有可能的 AdalException.ErrorCode 字符串属性值?

c# - Xamarin 页面 c# 中的自定义事件

xamarin - 缺少 xamarin.googleplayservices 引用

Android:滚动时如何更改折叠工具栏中的 View

android:nextFocusForward 在布局中被忽略

android - 如何更新 datepickerdialog android 中的日期?

xamarin - Xamarin 表单中的渐变按钮