gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:39 25 4
gpt4 key购买 nike

我正在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com