我正在 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);
我是一名优秀的程序员,十分优秀!