Android 全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1944656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:52:51  来源:igfitidea点击:

Android global variable

androidglobal-variables

提问by d-man

How can I create global variable keep remain values around the life cycle of the application regardless which activity running..

如何创建全局变量在应用程序的生命周期中保持保留值,而不管运行哪个活动..

回答by Jeff Gilfelt

You can extend the base android.app.Applicationclass and add member variables like so:

您可以扩展基android.app.Application类并添加成员变量,如下所示:

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication"attribute to the existing application tag):

在您的 android 清单中,您必须声明实现 android.app.Application 的类(将该android:name=".MyApplication"属性添加到现有的应用程序标记):

<application 
  android:name=".MyApplication" 
  android:icon="@drawable/icon" 
  android:label="@string/app_name">

Then in your activities you can get and set the variable like so:

然后在您的活动中,您可以像这样获取和设置变量:

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();

回答by Ramps

You can use a Singleton Patternlike this:

你可以使用Singleton Pattern这样的:

package com.ramps;

public class MyProperties {
private static MyProperties mInstance= null;

public int someValueIWantToKeep;

protected MyProperties(){}

public static synchronized MyProperties getInstance() {
        if(null == mInstance){
            mInstance = new MyProperties();
        }
        return mInstance;
    }
}

In your application you can access your singleton in this way:

在您的应用程序中,您可以通过以下方式访问您的单身人士:

MyProperties.getInstance().someValueIWantToKeep

回答by r1k0

You could use application preferences. They are accessible from any activity or piece of code as long as you pass on the Context object, and they are private to the application that uses them, so you don't need to worry about exposing application specific values, unless you deal with routed devices. Even so, you could use hashing or encryption schemes to save the values. Also, these preferences are stored from an application run to the next. Hereis some code examples that you can look at.

您可以使用应用程序首选项。只要您传递 Context 对象,它们就可以从任何活动或代码段访问,并且它们对于使用它们的应用程序是私有的,因此您无需担心暴露应用程序特定的值,除非您处理路由设备。即便如此,您也可以使用散列或加密方案来保存值。此外,这些首选项从一个应用程序运行到下一个应用程序存储。 下面是一些您可以查看的代码示例。

回答by mahasam

This global variable works for my project:

这个全局变量适用于我的项目:

public class Global {
    public static int ivar1, ivar2;
    public static String svar1, svar2;
    public static int[] myarray1 = new int[10];
}


//  How to use other or many activity
Global.ivar1 = 10;

int i = Global.ivar1;

回答by Dan Mikita

There are a few different ways you can achieve what you are asking for.

有几种不同的方法可以实现您的要求。

1.) Extend the application class and instantiate your controller and model objects there.

1.) 扩展应用程序类并在那里实例化您的控制器和模型对象。

public class FavoriteColorsApplication extends Application {

    private static FavoriteColorsApplication application;
    private FavoriteColorsService service;

    public FavoriteColorsApplication getInstance() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        application.initialize();
    }

    private void initialize() {
        service = new FavoriteColorsService();
    }

    public FavoriteColorsService getService() {
        return service;
    }

}

Then you can call the your singleton from your custom Application object at any time:

然后您可以随时从您的自定义 Application 对象调用您的单例:

public class FavoriteColorsActivity extends Activity {

private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_favorite_colors);

    service = ((FavoriteColorsApplication) getApplication()).getService();
    favoriteColors = service.findAllColors();

    ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
    adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
            favoriteColors);
    lv.setAdapter(adapter);
}

2.) You can have your controller just create a singleton instance of itself:

2.) 你可以让你的控制器只创建一个自己的单例实例:

public class Controller {
    private static final String TAG = "Controller";
    private static sController sController;
    private Dao mDao;

    private Controller() {
        mDao = new Dao();    
    }

    public static Controller create() {
        if (sController == null) {
            sController = new Controller();
        }
        return sController;
    }
}

Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

然后你可以从任何 Activity 或 Fragment 调用 create 方法,如果一个控制器不存在,它将创建一个新的控制器,否则它将返回预先存在的控制器。

3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

3.) 最后,Square 创建了一个漂亮的框架,它为您提供 Android 内的依赖注入。它被称为匕首。我不会在这里讨论如何使用它,但如果你需要那种东西,它会非常巧妙。

I hope I gave enough detail in regards to how you can do what you are hoping for.

我希望我提供了足够的细节,说明如何做你所希望的。

回答by kumar kundan

Try Like This:

像这样尝试:

Create a shared data class:

创建共享数据类:

SharedData.java

共享数据

import android.app.Application;

/**
 * Created by kundan on 6/23/2015.
 */
public class Globals {


    private static Globals instance = new Globals();

    // Getter-Setters
    public static Globals getInstance() {
        return instance;
    }

    public static void setInstance(Globals instance) {
        Globals.instance = instance;
    }

    private String notification_index;


    private Globals() {

    }


    public String getValue() {
        return notification_index;
    }


    public void setValue(String notification_index) {
        this.notification_index = notification_index;
    }



}

Declared/Initiaze an instance of class globally in those classes where you want to set/get data (using this code before onCreate()method):-

在要设置/获取数据的那些类中全局声明/初始化类的实例(在onCreate()方法之前使用此代码):-

Globals sharedData = Globals.getInstance();

Set data:

设置数据:

sharedData.setValue("kundan");

Get data:

获取数据:

String n = sharedData.getValue();

回答by san88

You can create a Global Classlike this:

你可以创建一个Global Class这样的:

public class GlobalClass extends Application{

    private String name;
    private String email;

    public String getName() {
        return name;
    }

    public void setName(String aName) {
        name = aName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String aEmail) {
        email = aEmail;
    }
}

Then define it in the manifest:

然后在清单中定义它:

<application
    android:name="com.example.globalvariable.GlobalClass" ....

Now you can set values to global variable like this:

现在您可以像这样将值设置为全局变量:

final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setName("Android Example context variable");

You can get those values like this:

您可以像这样获得这些值:

final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
final String name  = globalVariable.getName();

Please find complete example from this blog Global Variables

请从这个博客全局变量中找到完整的例子

回答by mahasam

// My Class Global Variables  Save File Global.Java
public class Global {
    public static int myVi; 
    public static String myVs;
}

// How to used on many Activity

Global.myVi = 12;
Global.myVs = "my number";
........
........
........
int i;
int s;
i = Global.myVi;
s = Global.myVs + " is " + Global.myVi;

回答by Alexandre

I checked for similar answer, but those given here don't fit my needs. I find something that, from my point of view, is what you're looking for. The only possible black point is a security matter (or maybe not) since I don't know about security.

我检查了类似的答案,但这里给出的答案不符合我的需求。从我的角度来看,我找到了您正在寻找的东西。唯一可能的黑点是安全问题(或可能不是),因为我不了解安全。

I suggest using Interface (no need to use Class with constructor and so...), since you only have to create something like :

我建议使用接口(不需要使用带有构造函数的类等等......),因为你只需要创建类似的东西:

public interface ActivityClass {

    public static final String MYSTRING_1 = "STRING";

    public static final int MYINT_1 = 1;

}

Then you can access everywhere within your classes by using the following:

然后,您可以使用以下方法访问类中的任何地方:

int myInt = ActivityClass.MYINT_1;
String myString = ActivityClass.MYSTRING_1;

回答by hexicle

Technically this does not answer the question, but I would recommend using the Room database instead of any global variable. https://developer.android.com/topic/libraries/architecture/room.htmlEven if you are 'only' needing to store a global variable and it's no big deal and what not, but using the Room database is the most elegant, native and well supported way of keeping values around the life cycle of the activity. It will help to prevent many issues, especially integrity of data. I understand that database and global variable are different but please use Room for the sake of code maintenance, app stability and data integrity.

从技术上讲,这并不能回答问题,但我建议使用 Room 数据库而不是任何全局变量。 https://developer.android.com/topic/libraries/architecture/room.html即使你“只”需要存储一个全局变量,这没什么大不了的,但使用 Room 数据库是最优雅的,原生且得到良好支持的方式,以在活动的生命周期中保持价值观。它将有助于防止许多问题,尤其是数据的完整性。我知道数据库和全局变量是不同的,但为了代码维护、应用程序稳定性和数据完整性,请使用 Room。