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


你可以像这样使用单例模式:

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;
    }
}

在你的应用程序中,你可以这样访问你的单例:

MyProperties.getInstance().someValueIWantToKeep

你可以扩展基本的android.app.Application类,并像这样添加成员变量:

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

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

在你的android manifest中,你必须声明实现android.app. application的类(添加android:name="。属性到现有的应用程序标签):

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

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

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

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

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


简单! !

那些你想作为全局变量访问的变量,你可以声明为静态变量。现在,你可以通过

classname.variablename;

public class MyProperties {
private static MyProperties mInstance= null;

static int someValueIWantToKeep;

protected MyProperties(){}

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

}

MyProperites.someValueIWantToKeep;

Thats It !;)


// 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;

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

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;

import android.app.Application;

public class Globals extends Application
{
    private static Globals instance = null;
    private static int RecentCompaignID;
    private static int EmailClick;
    private static String LoginPassword;
    static String loginMemberID;
    private static String CompaignName = "";
    private static int listget=0;
    //MailingDetails
    private static String FromEmailadd="";
    private static String FromName="";
    private static String ReplyEmailAdd="";
    private static String CompaignSubject="";
    private static int TempId=0;
    private static int ListIds=0;

    private static String HTMLContent="";
    @Override
    public void onCreate() 
    {
        super.onCreate();
        instance = this;
    }

    public static Globals getInstance()
    {
        return instance;
    }

    public void setRecentCompaignID(int objRecentCompaignID)
    {
        RecentCompaignID = objRecentCompaignID;
    }

    public int getRecentCompaignID() 
    {
        return RecentCompaignID;
    }

    public void setLoginMemberID(String objloginMemberID) 
    {
        loginMemberID = objloginMemberID;
    }

    public String getLoginMemberID() 
    {
        return loginMemberID;
    }

    public void setLoginMemberPassword(String objLoginPassword)
    {
        LoginPassword = objLoginPassword;
    }

    public String getLoginMemberPassword()
    {
        return LoginPassword;
    }

    public void setEmailclick(int id)
    {
        EmailClick = id;
    }

    public int getEmailClick() 
    {
        return EmailClick;
    }
    public void setCompaignName(String objCompaignName)
    {
        CompaignName=objCompaignName;
    }
    public String getCompaignName()
    {
        return CompaignName;
    }
    public void setlistgetvalue(int objlistget)
    {
        listget=objlistget;
    }
    public int getlistvalue()
    {
        return listget;
    }
    public void setCompaignSubject(String objCompaignSubject)
    {
         CompaignSubject=objCompaignSubject;
    }
    public String getCompaignSubject()
    {
        return CompaignSubject;
    }
    public void setHTMLContent(String objHTMLContent)
    {
        HTMLContent=objHTMLContent;
    }
    public String getHTMLContent()
    {
        return HTMLContent;
    }
    public void setListIds(int objListIds)
    {
        ListIds=objListIds;
    }
    public int getListIds()
    {
        return ListIds;
    }
    public void setReplyEmailAdd(String objReplyEmailAdd)
    {
        ReplyEmailAdd=objReplyEmailAdd;
    }
    public String getReplyEmailAdd()
    {
        return ReplyEmailAdd;
    }
    public void setFromName(String objFromName)
    {
        FromName=objFromName;
    }
    public String getFromName()
    {
        return FromName;
    }
    public void setFromEmailadd(String objFromEmailadd)
    {
        FromEmailadd=objFromEmailadd;
    }
    public String getFromEmailadd()
    {
        return FromEmailadd;
    }
}

如果可能的话,你应该在文件中声明你需要保持活跃的变量,这些变量没有被垃圾收集器清除或被OS卸载 要做到这一点,你必须用C/ c++编写代码,并编译为.so lib文件,并将其加载到MainActivity中。


有几种不同的方法可以达到你的要求。

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;
    }

}

然后你可以在任何时候从你的自定义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)。你可以让你的控制器只创建一个它自己的单例:

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;
    }
}

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

3)。最后,在Square上创建了一个灵活的框架,为你提供Android内部的依赖注入。它叫匕首。我不会在这里详细说明如何使用它,但如果你需要这类东西,它是非常灵巧的。

我希望我已经给出了足够的细节,告诉你如何去做你所希望的事情。


你可以像这样创建一个全局类:

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;
    }
}

然后在manifest中定义它:

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

现在你可以像这样设置全局变量的值:

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

你可以像这样得到这些值:

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

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


试着这样做:

创建共享数据类:

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;
    }



}

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

Globals sharedData = Globals.getInstance();

组数据:

sharedData.setValue("kundan");

得到的数据:

String n = sharedData.getValue();

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

我建议使用Interface(不需要使用带有构造函数的Class,所以…),因为你只需要创建如下内容:

public interface ActivityClass {

    public static final String MYSTRING_1 = "STRING";

    public static final int MYINT_1 = 1;

}

然后你可以使用以下命令访问类中的任何地方:

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

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.html Even 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.


使用SharedPreferences存储和检索全局变量。

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userid = preferences.getString("userid", null);