使用Mono Android的线程屏幕旋转?

使用Mono Android的线程屏幕旋转?,android,mono,xamarin.android,Android,Mono,Xamarin.android,在Commonware电子书AndroidV3.6第270页中,他讨论了使用旋转处理线程。他提供了一个解决方案,您可以创建一个内部静态类来保存您的状态,在工作流中调用detach,然后在屏幕旋转期间再次附加 问题是每次旋转都会破坏活动并在Android中重新创建,因此当您返回时,您的线程可能会引用已破坏的活动,从而为您访问要收集的对象集提供异常 我在Mono Android上试过这个,但没能成功,每次都有例外。我的问题,希望Jonathan Pryer读到这篇文章,是我如何在Mono Andro

在Commonware电子书AndroidV3.6第270页中,他讨论了使用旋转处理线程。他提供了一个解决方案,您可以创建一个内部静态类来保存您的状态,在工作流中调用detach,然后在屏幕旋转期间再次附加

问题是每次旋转都会破坏活动并在Android中重新创建,因此当您返回时,您的线程可能会引用已破坏的活动,从而为您访问要收集的对象集提供异常


我在Mono Android上试过这个,但没能成功,每次都有例外。我的问题,希望Jonathan Pryer读到这篇文章,是我如何在Mono Android中实现这一点?我已经在论坛上问了两次,都没有结果。所以我把它带到StackOverflow。我想发布实际代码,但我不想违反公共软件许可。所以请看一看书中的例子。

例外是什么?adb logcat的输出是什么

C#等价物与Java源代码相同但不同。例如,以下是Android示例项目默认Mono的“旋转感知”版本:

[Activity (Label = "Scratch.PreserveCount", MainLauncher = true)]
public class Activity1 : Activity
{
    CountInfo Info;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button> (Resource.Id.myButton);

        button.Click += delegate {
            SetButtonCount (button, Info.Count++);
        };

        Info = (CountInfo) LastNonConfigurationInstance;
        if (Info == null) {
            Info = new CountInfo {
                Count = 1,
            };
        } else {
            SetButtonCount (button, Info.Count);
        }
    }

    void SetButtonCount (Button button, int count)
    {
        button.Text = string.Format ("{0} clicks!", Info.Count);
    }

    public override Java.Lang.Object OnRetainNonConfigurationInstance ()
    {
        return Info;
    }

    class CountInfo : Java.Lang.Object {
        public int Count;
    }
}
[活动(Label=“Scratch.PreserveCount”,MainLauncher=true)]
公共课堂活动1:活动
{
CountInfo信息;
创建时受保护的覆盖无效(捆绑包)
{
base.OnCreate(bundle);
//从“主”布局资源设置视图
SetContentView(Resource.Layout.Main);
//从布局资源中获取我们的按钮,
//并在其上附加一个事件
Button Button=FindViewById(Resource.Id.myButton);
按钮。单击+=委派{
setButtoCount(按钮,Info.Count++);
};
Info=(CountInfo)LastNonConfigurationInstance;
if(Info==null){
Info=新CountInfo{
计数=1,
};
}否则{
SetButtonCount(按钮,信息计数);
}
}
无效设置按钮计数(按钮按钮,整数计数)
{
button.Text=string.Format(“{0}点击!”,Info.Count);
}
public override Java.Lang.Object OnRetainOnConfiguration实例()
{
退货信息;
}
类CountInfo:Java.Lang.Object{
公共整数计数;
}
}

这与Java示例的基本方法相同:该方法在处理活动之前由Android调用,因此我们从该方法返回“状态”。第一次调用该属性时,该属性将返回
null
,否则它将返回从
onretainonconfigurationinstance()
返回的最后一个值。谜题中唯一缺失的一点是,当我们将实例传递给Java时,“state”对象(
CountInfo
此处)必须从继承而来。

由于我没有Commonware电子书Android v3.6的副本,因此有一些代码来构建是很方便的。:-)看起来他在线上有这些示例:我会尽快在一个示例中为您提供这些示例,但我尝试使用线程,而不是Java示例中的任务。我一直得到的是一个关于泄漏窗口引用的错误,我认为这意味着我试图引用已处理的活动。我将在Xamarin论坛上继续此操作,接受您的回答以关闭此问题。