【问题标题】:Xamarin Android: get one app's state information from anotherXamarin Android:从另一个应用程序获取一个应用程序的状态信息
【发布时间】: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


    【解决方案1】:

    根据我的研究,我认为您可以在需要 Mehitabel 中的数据之前打开 Archy。这是关于在代码中打开应用程序的演示。

     Intent launchIntent = PackageManager.GetLaunchIntentForPackage("NewTestApp.NewTestApp");
                if (launchIntent != null)
                {
                    StartActivity(launchIntent);
    
                }
    

    注意:NewTestApp.NewTestApp 是 Archy 的包名。

    【讨论】:

    • 我得到了这个工作,有一些警告:1)当我拼写我的包名时效果更好。 2) Archy 的启动时间比预期的要长——从发送启动意图到收到对我的广播的响应超过 25 秒。 3)我不得不在我原来的问题中的 Mehitabel 代码中添加一个重试循环来处理(2),因为在 Archy 准备好之前发送的广播丢失了。
    • 事实证明,使用StartActivityForResult() 是一种更简单的方法。详情请见my answer to a related question
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 2020-12-15
    • 2012-11-16
    相关资源
    最近更新 更多