Xamarin.Forms Android 应用程序在外部 activity 启动后重新启动

Xamarin.Forms Android app restarts after external activity is launched

我的 Xamarin.Forms Android 应用程序中的一个功能允许用户从图库中选择照片(这是来自 XLabs 的 IMediaPicker 自定义控件显示原生图库activity,就像您在任何其他常规 Xamarin.Android 应用程序中所做的一样)。

The problem is that sometimes the device gets low on memory (again, normal stuff) and when the image is chosen, the MainActivityfrom XF is restarted (as expected) and the app starts in the main页面,而不是用户之前所在的页面。

我如何处理 Xamarin.Forms 中的这种情况?例如,从用户在打开图库 activity 之前所在的页面继续。

您可以尝试通过覆盖 OnSleep method 来保存应用程序的状态。

Xamarin Forms Samples中有一个实现示例。特别是检查 OnSleep 和 OnResume:

protected override void OnSleep()
{
    Debug.WriteLine ("OnSleep saving ResumeAtTodoId = " + ResumeAtTodoId);
    // the app should keep updating this value, to
    // keep the "state" in case of a sleep/resume
    Properties ["ResumeAtTodoId"] = ResumeAtTodoId;
}

protected override void OnResume()
{
    Debug.WriteLine ("OnResume");
    if (Properties.ContainsKey ("ResumeAtTodoId")) {
        var rati = Properties ["ResumeAtTodoId"].ToString();

        Debug.WriteLine ("   rati="+rati);
        if (!String.IsNullOrEmpty (rati)) {
            Debug.WriteLine ("   rati = " + rati);
            ResumeAtTodoId = int.Parse (rati);

            if (ResumeAtTodoId >= 0) {
                var todoPage = new TodoItemPage ();
                todoPage.BindingContext = Database.GetItem (ResumeAtTodoId);
                MainPage.Navigation.PushAsync (
                    todoPage, false); // no animation
            }
        }
    }
}