如何在应用程序的生命周期中创建全局变量,而不管哪个活动正在运行。
当前回答
如果可能的话,你应该在文件中声明你需要保持活跃的变量,这些变量没有被垃圾收集器清除或被OS卸载 要做到这一点,你必须用C/ c++编写代码,并编译为.so lib文件,并将其加载到MainActivity中。
其他回答
你可以像这样创建一个全局类:
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();
请从这个博客中找到完整的例子 全局变量
简单! !
那些你想作为全局变量访问的变量,你可以声明为静态变量。现在,你可以通过
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;
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.
您可以使用应用程序首选项。只要您传递Context对象,就可以从任何活动或代码段访问它们,并且它们对于使用它们的应用程序是私有的,因此您不需要担心暴露应用程序特定的值,除非您处理路由设备。即使如此,您也可以使用哈希或加密方案来保存值。此外,这些首选项将从一个应用程序运行到下一个应用程序运行。 下面是您可以参考的一些代码示例。
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。