0

我正在使用消息中心在整个应用程序中发送和接收消息/数据。该应用程序处理自定义文件扩展名并将它们加载到应用程序中并处理这些文件。

将文件导入应用程序有两种方法:

1-按下应用程序中的浏览按钮并选择文件(这工作正常)。

2-直接按文件,因为文件扩展名与应用程序相关联,应用程序打开并导入所选文件。这就是问题开始的地方。

如果应用程序之前没有打开并且不在后台(这意味着还没有订阅者),则应用程序启动并且不执行任何操作,如预期的那样。应用程序将所选文件发送给订阅者,但由于表单未完成打开(MainActivity或 AppDelagate 之后执行的页面和视图模型),还没有可用的订阅者。

如果应用程序在后台,单击文件会打开应用程序并按预期工作。

我知道这个问题,但我不知道如何解决它。有什么建议么?

这是MainActivity.cs在 Android 中:

 protected override async void OnNewIntent(Intent intent)
        {
            if (intent?.Data == null)
                return;

            // Open a stream from the URI 
            var lasStream = ContentResolver.OpenInputStream(intent.Data);

            // Save it over 
            var memStream = new MemoryStream();
            await lasStream.CopyToAsync(memStream);
            var byteArray = memStream.ToArray();

            MessagingCenter.Send(byteArray, "ByteArrayReceived");
        }

此方法在应用程序的其中一个 ViewModel 中调用:

private async Task ByteArrayReceived(byte[] byteArray)
    {
        // Handle incoming file as a byte array
    }

更新:

我认为问题不是那么清楚。我将尝试解释更多。

我想要做的是,当用户选择一个外部文件(这可能是一个 txt 文件或其他文件)时,这个应用程序应该启动并将所选文件的内容加载到应用程序中。

正在检测传入文件,当应用程序打开时首先MainActivity.cs执行,这意味着还没有任何订阅者可用,因为应用程序尚未完成加载并且尚未调用订阅者方法。订阅者方法在MainPageView.cs

我知道应该在发送消息之前调用订阅者方法,但我该如何在MainActivity.csor中执行此操作AppDelagate.cs

更新 2:

MainPageView 在 MainActivity.cs 执行后被调用。

这是MainActivity.cs

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.Window.RequestFeature(WindowFeatures.ActionBar);
        base.SetTheme(Resource.Style.MainTheme);

        if (Intent.Action == Intent.ActionSend || Intent.Action == Intent.ActionView)
            HandleIntent(Intent);

        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        LoadApplication(new App());
    }

这是App.cs

   public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new MainPageView());
    }
4

1 回答 1

0

我发现的一种解决方案是您可以在X秒后使用Device.StartTimer发送消息:

protected override async void OnNewIntent(Intent intent)
{
    if (intent?.Data == null)
        return;

    // Open a stream from the URI 
    var lasStream = ContentResolver.OpenInputStream(intent.Data);

    // Save it over 
    var memStream = new MemoryStream();
    await lasStream.CopyToAsync(memStream);
    var byteArray = memStream.ToArray();

    // run task after 2 second
    Device.StartTimer(TimeSpan.FromSeconds(2), () =>
    {
        MessagingCenter.Send(byteArray, "ByteArrayReceived");

        // No longer need to recur. Stops firing task
        return false;
    });
}
于 2020-06-30T06:09:37.557 回答