수색…


소개

유니버설 윈도우 10 애플 리케이션 라이프 사이클은 다음과 같은 세 가지 상태로 구성됩니다. 1) 실행 중 - 응용 프로그램이 현재 사용 중임 2) 실행되지 않음 - 응용 프로그램이 닫히고 메모리에서 제거됨 3) 일시 중단됨 - 응용 프로그램 상태가 고정되었지만 여전히 메모리에 있음 [! [ 여기에 이미지 설명 입력] [1]] [1] [1] : https://i.stack.imgur.com/x7MCl.png 위 그림에서 볼 수 있듯이 하나의 상태에서 다음 상태로 다른. 예제 섹션에서는이를 처리하는 방법을 보여줍니다.

비고

MSDN 블로그의 두 가지 좋은 기사를 참조하는 것이 좋습니다.

  1. https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/app-lifecycle
  2. https://blogs.windows.com/buildingapps/2016/04/28/the-lifecycle-of-a-uwp-app/#RqKAKkevsAPIvBUT.97

"실행 중"상태 처리

"Running"상태로 이동할 때이 이벤트와 연결된 특수한 핸들러가 있습니다 : "App.xaml.cx"클래스 열기 및 "OnLaunched"메소드보기 - 이것은 "Terminaded"상태에서 사용자가 응용 프로그램을 열 때 활성화됩니다 :

protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (rootFrame == null)
        {
            // Create a Frame to act as the navigation context and navigate to the first page
            rootFrame = new Frame();

            rootFrame.NavigationFailed += OnNavigationFailed;

           //You can get information about previous state of the app:

            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //The app was previously suspended but was then shutdown 
                //at some point because the system needed to reclaim memory.
            }
            if (e.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
            {
                //The user closed the app with the close gesture in tablet mode,
                //or with Alt+F4.When the user closes the app, it is first suspended
                //and then terminated.
            }
            if (e.PreviousExecutionState == ApplicationExecutionState.NotRunning)
            {
                //An app could be in this state because it hasn't been launched since the last time
                //the user rebooted or logged in. It can also be in this state if it was running 
                //but then crashed, or because the user closed it earlier.
            }
            if (e.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                //The app was already open when the user tried to launch it again
            }
            if (e.PreviousExecutionState == ApplicationExecutionState.Suspended)
            {
                //The user either minimized or switched away from your app
                //and didn't return to it within a few seconds.
            }

            // Place the frame in the current Window
            Window.Current.Content = rootFrame;
        }

        //When available system resources allow, the startup performance of Windows Store
        //apps on desktop device family devices is improved by proactively launching
        //the user’s most frequently used apps in the background. A prelaunched app 
        //is put into the suspended state shortly after it is launched.Then, when the
        //user invokes the app, the app is resumed by bringing it from the suspended
        //state to the running state--which is faster than launching the app cold.
        //The user's experience is that the app simply launched very quickly.
        if (e.PrelaunchActivated == false)
        {
            if (rootFrame.Content == null)
            {
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            Window.Current.Activate();
        }
    }

"일시 중단"상태 처리

"Suspened"상태로 이동할 때이 이벤트와 연결된 특수한 핸들러가 있습니다 : "App.xaml.cx"클래스를 열고 "App"생성자를 봅니다 - 이벤트 핸들러가 있습니다 :

public App()
    {
        this.InitializeComponent();
        //Handle suspending operation with event handler:
        this.Suspending += OnSuspending;
    }

이제 정지 이벤트를 처리 할 수 ​​있습니다.

private Dictionary<string, object> _store = new Dictionary<string, object>();
private readonly string _saveFileName = "store.xml";
private async void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        _store.Add("timestamp", DateTime.Now);
        await SaveStateAsync();
        //TODO: Save application state and stop any background activity
        //Here you can use  await SuspensionManager.SaveAsync();
        //To read more about saving state please refer to below MSDN Blog article:
        //https://blogs.windows.com/buildingapps/2016/04/28/the-lifecycle-of-a-uwp-app/#RqKAKkevsAPIvBUT.97
        deferral.Complete();
    }

    private async Task SaveStateAsync()
    {
        var ms = new MemoryStream();
        var serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
        serializer.WriteObject(ms, _store);

        var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(_saveFileName, CreationCollisionOption.ReplaceExisting);

        using (var fs = await file.OpenStreamForWriteAsync())
        {
            //because we have written to the stream, set the position back to start
            ms.Seek(0, SeekOrigin.Begin);
            await ms.CopyToAsync(fs);
            await fs.FlushAsync();
        }
    }

"상태 재개"상태 처리

사용자는 응용 프로그램을 "일시 중단됨"상태에서 열 수 있습니다. 그것을 할 때 "OnResuming"이벤트 핸들러가 사용됩니다. "App.xaml.cs"클래스에서 :

public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        //Handle resuming operation:
        this.Resuming += App_Resuming;
    }

private void App_Resuming(object sender, object e)
    {
        //Do some operation connected with app resuming for instance refresh data
    }


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow