简体   繁体   English

如何在Android的所有活动中维护变量?

[英]How to maintain variables across all the activities in Android?

I have an application which has 3 activities. 我有一个包含3个活动的应用程序。

  • Activity1 活动1
  • Activity2 活动2
  • Activity3 活动3

When the user opens the application, I am fetching the user's location and storing it in a static variable in a Helper class. 当用户打开应用程序时,我正在获取用户的位置并将其存储在Helper类的静态变量中。 Lets say the variable is latlng. 可以说该变量是latlng。 Now I need to access the value of latlng variable in Activity2. 现在,我需要在Activity2中访问latlng变量的值。 So i simply use Helper.latlng in Activity2 . 所以我只是在Activity2中使用Helper.latlng。 It works fine most of the time. 大多数情况下,它都能正常工作。

But if I press the home button and open some other application, and then come back to my application, my application force closes. 但是,如果我按下主页按钮并打开其他应用程序,然后返回到我的应用程序,我的应用程序将关闭。 After debugging I find out that latlng variable is becoming null in Activity2. 调试后,我发现latlng变量在Activity2中变为空。

So, after going through various documentations, I came to find out that if a lot of applications are running, then Android OS may kill some applications. 因此,在浏览了各种文档之后,我发现如果许多应用程序正在运行,那么Android OS可能会杀死某些应用程序。 So basically if I open some other application, my current activity is destroyed by the OS. 因此,基本上,如果我打开其他应用程序,操作系统将破坏我当前的活动。 So automatically all my static variables are gone. 因此,我所有的静态变量都自动消失了。

One way to overcome this is continue using static variables with onSavedInstanceState method which is called when the activity is getting destroyed. 解决此问题的一种方法是继续使用带有onSavedInstanceState方法的静态变量,该方法将在活动被销毁时调用。

   public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LatLng latLng  = Helper.latlng;
        outState.putParcelable("latlng",latLng);
    }

And retrieve it using 并使用

 if( savedInstanceState != null ) {
            Helper.latlng = savedInstanceState.getParcelable("latlng");
        }

I am really confused whether I should go with the above approach. 我真的很困惑是否应该采用上述方法。 Is there any other way to use a variable across different activities in Android. 还有其他方法可以在Android中的不同活动之间使用变量。 I can from my experience say that using static variables is not a safe bet. 根据我的经验,我可以说使用静态变量不是一个安全的选择。

Just to get the most important part out of the way: You should NEVER use static variables in Android unless you know exactly what you are doing. 只是为了避开最重要的部分:除非您确切知道自己在做什么,否则绝对不要在Android中使用静态变量。 Otherwise you are going to create memory leaks and a whole other slew of problems. 否则,您将造成内存泄漏和一系列其他问题。

If you want to pass data to another Activity you should use Intents. 如果要将数据传递到另一个活动,则应使用Intent。

Method calls always have additional overhead. 方法调用总是有额外的开销。 Accessing a field directly will always be faster. 直接访问字段总是会更快。 But this does not mean that you should abandon getters and setters all together. 但这并不意味着您应该一起放弃吸气剂和吸气剂。

For example look at this class Example: 例如,查看此类示例:

public class Example { 

private String text;

public String getText() {
    return text;
} 

public void setText(String text) {
    this.text = text;
} 

public void doSomething() { 
    ... 
} } 

Inside doSomething() you should work with the field directly. 在doSomething()内部,您应该直接使用该字段。 Calling the getters and setters in there would not be the way to go since that would require additional overhead each time you call one. 调用getter和setter方法是没有办法的,因为每次调用一个方法都需要额外的开销。

If you are using the Example class inside another class like below you should use the getter and setter methods: Example instance = new Example(); instance.setText("some text"); ... String text = instance.getText(); 如果在另一个类似下面的类中使用Example类,则应使用getter和setter方法: Example instance = new Example(); instance.setText("some text"); ... String text = instance.getText(); Example instance = new Example(); instance.setText("some text"); ... String text = instance.getText();

Making the field public and accessing it directly like instance.text would be bad. 将该字段公开并像instance.text一样直接访问它会很糟糕。

BUT any modern device has so much computing power that the overhead generated by a method call is completely negligible. 但是任何现代设备都具有如此大的计算能力,以至于方法调用所产生的开销可以完全忽略不计。 The DOC do state that you should avoid using getters and setters in performance critical places, but that rule is from a time when most Android phones had 128 MB RAM. DOC确实指出,您应该避免在性能至关重要的地方使用吸气剂和吸气剂,但这是从大多数Android手机具有128 MB RAM的时间开始的。 The main reason you should adhere to the rules I explained above is just one thing: coding style. 您应该遵守我上面解释的规则的主要原因仅仅是一件事:编码样式。

Your first concern should always be to write clean, readable and maintainable code. 您首先要关心的是编写干净,可读和可维护的代码。

One of the ways of doing it is using the SharedPreferences storage in android. 做到这一点的方法之一是使用android中的SharedPreferences存储。

SharedPreferences pref =
getApplicationContext().getSharedPreferences("LocationPrefs", MODE_PRIVATE); 

Editor editor = pref.edit();
// Save latLang as a string variable
editor.putString("latLang", "string value of latLang");  

// Save the changes
editor.commit();

You can retrieve the results in this way, 您可以通过这种方式检索结果,

String latLang = pref.getString("latLang", null); 

There are few ways of passing data between Activities. 在活动之间传递数据的方法很少。

  1. SharedPreferences 共享首选项
  2. SQLite SQLite的
  3. Saving to file 保存到文件
  4. Intent with putExtra 使用putExtra的意图

In Android environment user can always delete app data, so you need to be prepared for that anyway 在Android环境中,用户始终可以删除应用数据,因此无论如何您都需要为此做好准备

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM