我有一个包含三项 Activity 的应用程序。这是我的 Activity 生命周期:Activity1 -> Activity2 -> Activity3。我的所有 Activity 都使用“完全相同”的偏好。 所以我创建了一个扩展类,用于我的所有 Activity 。 示例
public class myPreferences extends Activity{
protected string PlayerName;
protected float maxPlayerHealth;
protected float minPlayerHealth;
// there are about 15 variables
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getSharedPreferences("general_settings", Context.MODE_PRIVATE);
PlayerName = prefs.getString("PlayerName", null);
maxPlayerHealth = prefs.getFloat("PlayerName", 0.0f);
minPlayerHealth = prefs.getFloat("PlayerName", 0.0f);
//etc for rest of my preferences
}
这是我的每项 Activity 的示例。
public class Activity1 extends myPreferences{
}
public class Activity2 extends myPreferences{
}
public class Activity3 extends myPreferences{
}
所以我的问题是,在我的类中使用静态变量是否更好,并且在我的应用程序中仅运行一次sharedPreferences。示例我将检查玩家名称是否为空。
public class myPreferences extends Activity{
protected static string PlayerName;
protected static float maxPlayerHealth;
protected static float minPlayerHealth;
// there are about 15 variables
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(PlayerName ==null)
{
SharedPreferences prefs = this.getSharedPreferences("general_settings", Context.MODE_PRIVATE);
PlayerName = prefs.getString("PlayerName", null);
maxPlayerHealth = prefs.getFloat("PlayerName", 0.0f);
minPlayerHealth = prefs.getFloat("PlayerName", 0.0f);
//etc for rest of my preferences
}
}
两种方法哪一种更好? 1)内存使用情况如何?静态变量会占用更多内存吗?内存泄漏有风险吗? 2)两种方法哪一种性能更好?我认为如果我不总是阅读我的偏好,情况会稍微好一些。 3)我应该使用私有(private)签名而不是 protected 签名还是没关系? 4)如果我的所有 Activity 同时在堆栈中打开,变量将被重新创建3次?每个扩展 myPreferences 类的 Activity 都有一个?
最佳答案
还有很多事情要讲,但我会尽力:
What about memory usage?
在Java中,当我们只声明类类型的变量时,只创建一个引用(不会为对象分配内存)。为了给一个对象分配内存,我们必须使用new()。当您创建静态变量时,会使用 Java 中的堆栈内存。它包含特定于方法的原始值以及对堆中从该方法引用的对象的引用。对该内存的访问按照后进先出 (LIFO) 顺序进行。它的基本含义是,一旦您创建静态变量,就会为其分配一 block 内存,并且该内存将一直存在,直到您的应用程序关闭为止。
Static variables will use more memory? Is it risky for memory leaks?
更多内存?不!但在应用程序关闭之前,它基本上会分配一 block 内存。 内存泄漏有风险吗?
- 是的,这可能是因为它可能会创建一个循环依赖关系,这可能不会让你的对象类型被销毁,我可能是错的,但它不会发生在你的案例。
Which of the two methods will have better performance? I think if I don't read always my preferences it will be slightly better.
据我所知,静态可能具有更好的性能,因为您将把它放在变量中,而不必每次都从包中获取它。
Should I use a private signature instead of protected or it doesn't matter
派生类不会继承对私有(private)数据成员的访问权限。但是,它确实继承了一个完整的父对象,其中包含该类声明的任何私有(private)成员。因此,您可以根据您的用例来决定。
If all my activities are open in a stack at the same time, variables will be recreated 3 times? One for each activity which extends the class myPreferences?
如果项目是静态的,它将仅创建一次,静态变量就像一次性的东西。 每个扩展 myPreferences 类的 Activity 都有一个
- 不,不会
关于java - 使用扩展类的多个 Activity 的 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55899766/