如何在应用程序的生命周期中创建全局变量,而不管哪个活动正在运行。
当前回答
// 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;
其他回答
你可以像这样使用单例模式:
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
简单! !
那些你想作为全局变量访问的变量,你可以声明为静态变量。现在,你可以通过
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 !;)
试着这样做:
创建共享数据类:
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();
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.
如果可能的话,你应该在文件中声明你需要保持活跃的变量,这些变量没有被垃圾收集器清除或被OS卸载 要做到这一点,你必须用C/ c++编写代码,并编译为.so lib文件,并将其加载到MainActivity中。
推荐文章
- 安卓视图模型与视图模型
- Android的clipToPadding属性做什么?
- 导航抽屉:如何在启动时设置所选项目?
- 在XML中“图像上缺少contentDescription属性”
- 在Android SQLite中处理日期的最佳方法
- 读取Android APK的包名
- Android-Facebook应用程序的键散列
- 登出时,清除活动历史堆栈,防止“返回”按钮打开已登录的活动
- 如何改变标题的活动在安卓?
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout