C# 保存我的活动xamarin.android的状态

C# 保存我的活动xamarin.android的状态,c#,android,visual-studio,android-activity,xamarin,C#,Android,Visual Studio,Android Activity,Xamarin,我想在有人关闭应用程序时保存此活动的状态。它只包含一个ListActivity simplelistitemchecked namespace XamarinScanner { [Activity(Label = "@string/scanHistory", ScreenOrientation = ScreenOrientation.Portrait)] public class ScanHistoryActivity : ListActivity {

我想在有人关闭应用程序时保存此活动的状态。它只包含一个ListActivity simplelistitemchecked

   namespace XamarinScanner
     {
      [Activity(Label = "@string/scanHistory", ScreenOrientation = ScreenOrientation.Portrait)]
     public class ScanHistoryActivity : ListActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        var codes = Intent.Extras.GetStringArrayList("Codes");

        codes.ToList();
        ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItemChecked, codes);
        ListView lv = FindViewById<ListView>(Android.Resource.Id.List);
        lv.ChoiceMode = ChoiceMode.Multiple;

        foreach (var c in codes)
        {
            if (c.Contains("Success"))
            {
                int position = codes.IndexOf(c);
                lv.SetItemChecked(position, true);
            }
        }
    }
}
当用户关闭应用程序时,您的意思是什么?你是说当他关闭一段时间后再打开它,还是当应用程序完全关闭时?
如果您指的是第二个,那么应该使用OnDestroy“保存”状态,并在下次加载OnCreate。您必须手动创建保存和加载过程(使用数据库?SharedReferences?由您决定)
对于活动生命周期

也要经常发布你迄今为止尝试过的,它不想要的,以及你期望的确切结果

在OnDestroy上存储值的一种简单方法是使用SharedReferences:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutBoolean ("keyName", _bool);
// editor.Commit();    // applies changes synchronously on older APIs
editor.Apply();        // applies changes asynchronously on newer APIs
使用以下命令访问保存的值:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
_bool = prefs.GetBoolean ("keyName");
_int = prefs.GetInt ("keyName");
_string = prefs.GetString ("keyName");

你自己也试过寻找答案吗?这并不是一件不同寻常的事情。是的,用不同的例子尝试了几次,但没有成功。对xamarin、c#和一般代码来说都是非常新的!好吧,在这样一个开放式的问题上,你不会有太多的运气得到帮助。您需要准确地解释您尝试了什么以及出现了什么问题,否则您只是要求他人为您完成工作。只有创建了OnSaveInstanceState的版本,您才能在OnDestroy上保存状态。请在问题上添加代码,而不是在注释中,评论不是为了大讨论,而是为了小的修改,我应该把代码放在哪里?关闭应用程序时保存所有应用程序数据是否不正常?我对这个很陌生!您可以将此代码放在OnDestroy上保存数据,放在OnCreate上检索数据。我不知道你的具体情况,但保存应用程序状态通常是通过SharedReferences或数据库或其他存储当前值的方式完成的。通常,当我希望用户能够保存一些状态或数据时,我会为此设置一个功能(保存设置/按钮),我不会将其保存在OnDestroy上
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
_bool = prefs.GetBoolean ("keyName");
_int = prefs.GetInt ("keyName");
_string = prefs.GetString ("keyName");