【发布时间】:2018-12-18 21:54:57
【问题描述】:
我有两个 Xamarin Android 应用 - 我们称它们为“Archy”和“Mehitabel”。
Archy 有一些持久的状态信息(假设是为了论证,在 SQLite DB 中)。
如果 Mehitabel 发生某件事,她需要知道该状态信息的一部分。
为了完成这项壮举,我让 Mehitabel 向 Archy 发送了一个意图。 Archy 有一个广播接收器,它可以听到它,收集必要的状态,并将不同的意图返回给 Mehitabel。
这是 Archy 的代码:
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new [] { "com.example.Archy.SendStateToMehitabel"})]
public class StateQueryReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var msg = new Intent("com.example.Mehitabel.StateFromArchy");
msg.PutExtra("ImportantStateInfo", GetSomeState());
context.SendBroadcast(msg);
}
}
这是来自 Mehitabel 的代码:
private async Task AskArchyForState()
{
var filter = new IntentFilter("com.example.Mehitabel.StateFromArchy");
var csrc = new TaskCompletionSource<bool>();
var rcvr = new ActionBroadcastReceiver((context, intent) =>
{
State = intent.GetStringExtra("ImportantStateInfo");
csrc.TrySetResult(State != null);
});
RegisterReceiver(rcvr, filter);
var msg = new Intent("com.example.Archy.SendStateToMehitabel");
SendBroadcast(msg);
var task = await Task.WhenAny(csrc.Task, Task.Delay(Timeout));
UnregisterReceiver(rcvr);
if (task != csrc.Task)
bomb("Archy has not answered state query after {0}ms", Timeout);
if (!csrc.Task.IsCompletedSuccessfully || csrc.Task.Result == false)
bomb("failed to get all necessary state from Archy");
}
只要 Archy 实际运行(即显示在“最近”列表中),一切都很好。如果 Archy 没有运行,Archy 的接收器代码永远不会执行,Mehitabel 会超时。
我希望我遗漏了一些简单的东西(比如接收器属性之一中的标志,或者 com.example.Archy.SendStateToMehitabel 意图中的一些秘密调味料)。
你能告诉我这里缺少什么吗?
我是否需要使用完全不同的方法(例如在 Archy 中使用 Mehitabel StartActivityForResult() 活动,或者使用在启动时启动并一直运行的服务)?
【问题讨论】:
标签: android xamarin android-intent xamarin.android android-broadcastreceiver