我正在使用Dependency Service来获得接口的平台特定实现 . 假设我有以下界面:
public interface IMyInterface
{
bool IsEnabled { get; set; }
}
我的Android项目中的实现类:
[assembly: Dependency(typeof(MyClass))]
namespace App.Droid
{
class MyClass : IMyInterface
{
public bool IsEnabled { get; set; }
}
}
在代码中的某个时刻,我将 IsEnabled
设置为 true
.
之后,我开始一项新的活动,让我的应用程序转到后台:
Intent intent = new Intent();
intent.SetAction(action);
intent.SetFlags(ActivityFlags.NewTask);
MainActivity.Instance.StartActivity(intent);
当我的应用程序返回到前台时,我访问属性 IsEnabled
并且得到 false
而不是 true
. 这实际上发生在强制类的每个属性和私有字段中 . 当我离开应用程序进行新活动时,这些属性是否被垃圾收集?
我找到解决此问题的唯一方法是使所有支持字段 static
,但这会在代码中产生大量开销,如果我知道这种行为的原因,这可能是不必要的 .
1 回答
不太了解你的问题的 Headers .
If 您使用单例模式,您可以在需要时根据唯一的实例化对象提取属性 . 如下所示:
If not ,你可以使用
Properties
(https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.application.properties?view=xamarin-forms)toto)访问数据 . 就像这样:您可能会参与
lifecycles
和notifications
的使用 . 如果有大量数据,请考虑使用SQLite
数据库来保存此数据 . 可以参考此链接here更多:在Xamarin.Android中,您还可以尝试
lifecycles
来显示已保存的数据 . 像OnResume
方法一样显示数据 .