首页 文章

获取UWP应用程序的生命周期

提问于
浏览
0

我正在创建一个进程内UWP应用服务,以及另一个(桌面)客户端程序,它通过应用服务与应用程序通信 . 客户端程序想要知道UWP应用程序当前是否正在运行(在前台),在桌面应用程序打开 AppServiceConnection 之前是否已经在后台运行,被暂停或根本没有运行 . 换句话说,应用程序需要能够通过应用程序服务传达它在_2765658中的位置 .

有没有什么方法可以以编程方式检测应用程序的生命周期状态,除了实现我自己的状态变量,每当引发一个相关事件时我都会更新它?它似乎应该是可能的,但我找不到它的API . 显然它永远不会告诉你你当前被暂停或没有运行,但能够区分“暂停除了这个应用程序服务任务”和“主动在前台运行”之间的区别将是有用的 .

1 回答

  • 0

    客户端程序想知道UWP应用程序当前是否正在运行(在前台),在桌面应用程序打开AppServiceConnection之前是否已在后台运行

    在桌面应用程序打开 AppServiceConnection 连接之前,客户端应该无法与应用程序服务提供商通信,因为UWP应用程序是沙箱 . 获取其中的应用服务提供商的当前状态对客户端应用程序没有用处 . 如果客户端桌面应用程序是.NET Framework,您可以尝试使用Process.Responding属性来获取服务提供者进程状态 . 例如,如果 Process.Responding 为true,则服务提供者为"actively running in the foreground",如果为false,则应暂停提供者,如果无法找到提供者进程,则应终止提供者 .

    static void Main(string[] args)
    { 
        Process[] processes = Process.GetProcesses();
    
        foreach (Process process in processes)
        {
           if (process.ProcessName == "AppServicesProvider")
                Console.WriteLine("Process Name: {0}, Responding: {1}", process.ProcessName, process.Responding);
        } 
        Console.ReadLine();
    }
    

    换句话说,应用程序需要能够通过应用程序服务传达它在其生命周期中的位置 .

    如果您的意思是app服务,那么当应用程序的执行状态发生变化时,您提到的在app data中存储状态的方式应该可以正常工作 . 看起来您不想使用它,但实际上触发的状态匹配事件句柄表明应用程序的执行状态已更改 .

    private async void App_Suspending(object sender, SuspendingEventArgs e)
    {
        SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
        Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        localSettings.Values["currentlife"] = "Suspended";
        deferral.Complete();
    }
    private async void OnAppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
    {
        var messageDeferral = args.GetDeferral();
        Windows.Storage.ApplicationDataContainer localSettings =Windows.Storage.ApplicationData.Current.LocalSettings;
        Object value = localSettings.Values["currentlife"];
        try
        {
            var input = args.Request.Message; 
            //Create the response
            var result = new ValueSet(); 
            result.Add("result", value);
            //Send the response
            await args.Request.SendResponseAsync(result);
        }
        finally
        {
            //Complete the message deferral so the platform knows we're done responding
            messageDeferral.Complete();
        }
    }
    

相关问题