简体   繁体   English

从后台任务启动UWP应用

[英]Launch an UWP app from Background Task

I have created an UWP app with out-of-process background task following this link 我通过此链接创建了一个UWP应用,其中包含进程外后台任务

out of process background task 进程外后台任务

This is My Background Task 这是我的后台任务

namespace MyTask
{
    public sealed class FirstTask : IBackgroundTask
    {
        private BackgroundTaskDeferral backgroundTaskDeferral;
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            DefaultLaunch();
        }

        async void DefaultLaunch()
        {
            // The URI to launch
            var uriBing = new Uri("mytempapp://test");
            try
            {
                // Launch the URI
                var success = await Windows.System.Launcher.LaunchUriAsync(uriBing);  // Throws Error 
             }
            catch (Exception e)
            {

            }
        }

    }
}

This background Task is activated on Timezone Change which works fine 后台任务在时区更改时激活,效果很好

BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "FirstTask", TaskEntryPoint = "MyTask.FirstTask" };
taskBuilder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
BackgroundTaskRegistration myFirstTask = taskBuilder.Register();

Problem is when DefaultLaunch() is called it throws error. 问题是调用DefaultLaunch()时会引发错误。 Ideal case will be it should open my App registered with a URI scheme 理想情况是它将打开我的以URI方案注册的应用程序

System.Runtime.InteropService.COMException(0x80070578) invalid window Handler

This API must be called from a thread with a CC

Unfortunately you cannot launch a URI from a background task. 不幸的是,您无法从后台任务启动URI。 This would be disruptive for the user, because she could not be able to identify why the app is starting and could be misused easily . 这将对用户造成破坏,因为她无法识别启动应用程序的原因,并且很容易被滥用 Even worse, from a background thread the user could not be able to identify which app caused the launch (to be able to uninstall the malicious one). 更糟糕的是,用户无法从后台线程识别导致启动的应用程序 (从而能够卸载恶意应用程序 )。

As the error message states, this API can be called only from an UI thread - meaning a thread associated with an app view. 如错误消息所述, 只能从UI线程 (即与应用视图关联的线程)中调用此API。 Background task has no app view association and hence cannot launch an URI. 后台任务没有应用程序视图关联,因此无法启动URI。 same goes for LaunchFileAsync and other Launcher APIs. LaunchFileAsync和其他Launcher API也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM