如何在应用程序的生命周期中创建全局变量,而不管哪个活动正在运行。
当前回答
您可以使用应用程序首选项。只要您传递Context对象,就可以从任何活动或代码段访问它们,并且它们对于使用它们的应用程序是私有的,因此您不需要担心暴露应用程序特定的值,除非您处理路由设备。即使如此,您也可以使用哈希或加密方案来保存值。此外,这些首选项将从一个应用程序运行到下一个应用程序运行。 下面是您可以参考的一些代码示例。
其他回答
试着这样做:
创建共享数据类:
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();
简单! !
那些你想作为全局变量访问的变量,你可以声明为静态变量。现在,你可以通过
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 !;)
你可以像这样使用单例模式:
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
使用SharedPreferences存储和检索全局变量。
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userid = preferences.getString("userid", null);
这个全局变量适用于我的项目:
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;
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 如何关闭mysql密码验证?
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用