我正在开发xamarin.android中的辅助功能服务。 一切都很好,但我想要服务上的广播接收器。 我知道我必须从广播接收器派生我的可访问性服务,但这是不可能的,因为该服务已经从Android.AccessibilityService派生。 实际上,当用户对主要活动进行一些配置更改时,我想提出一个广播接收器,我的可访问性服务应该监听。 那么,对此有什么想法吗?
答案 0 :(得分:4)
在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);