Launch an UWP app from Background Task

1

I have created an UWP app with out-of-process background task following this link

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. Ideal case will be it should open my App registered with a URI scheme

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

This API must be called from a thread with a CC
c#
uwp
asked on Stack Overflow Jan 18, 2018 by MyTwoCents

1 Answer

4

Unfortunately you cannot launch a URI from a background task. 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. Background task has no app view association and hence cannot launch an URI. same goes for LaunchFileAsync and other Launcher APIs.

answered on Stack Overflow Jan 18, 2018 by Martin Zikmund

User contributions licensed under CC BY-SA 3.0