首页 文章

Xamarin.Forms依赖服务和活动

提问于
浏览
0

我正在使用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 回答

  • 0

    不太了解你的问题的 Headers .

    If 您使用单例模式,您可以在需要时根据唯一的实例化对象提取属性 . 如下所示:

    public class Singleton
        {
            // Define a static variable to hold an instance of the class
            private static Singleton uniqueInstance;
    
            // Define a private constructor so that the outside world cannot create instances of the class
            private Singleton()
            {
            }
    
            /// <summary>
            /// Define public methods to provide a global access point, and you can also define public properties to provide global access points
            /// </summary>
            /// <returns></returns>
            public static Singleton GetInstance()
            {
                // Create if the instance of the class does not exist, otherwise return directly
                if (uniqueInstance == null)
                {
                    uniqueInstance = new Singleton();
                }
                return uniqueInstance;
            }
        }
    

    If not ,你可以使用 Propertieshttps://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.application.properties?view=xamarin-forms)toto)访问数据 . 就像这样:

    private void SaveConnectionData(JSON.Connection C)
                        {
                            App.Current.Properties[Cryptography.Encryption("AccessToken")] = Cryptography.Encryption(C.Access_token);
                            App.Current.Properties[Cryptography.Encryption("ExpiresIn")] = Cryptography.Encryption(C.Expires_in.ToString());
                            App.Current.Properties[Cryptography.Encryption("TokenType")] = Cryptography.Encryption(C.Token_type);
                            App.Current.Properties[Cryptography.Encryption("Scope")] = Cryptography.Encryption(JsonConvert.SerializeObject(C.Scope));
                            App.Current.Properties[Cryptography.Encryption("RefreshToken")] = Cryptography.Encryption(C.Refresh_token);
                            App.Current.SavePropertiesAsync();
                        }
    

    您可能会参与 lifecyclesnotifications 的使用 . 如果有大量数据,请考虑使用 SQLite 数据库来保存此数据 . 可以参考此链接here

    更多:在Xamarin.Android中,您还可以尝试 lifecycles 来显示已保存的数据 . 像 OnResume 方法一样显示数据 .

相关问题