如何在android模块中使用全局变量
我在库中使用了singleton来保存数据,但有时发现当用户获得singleton变量时,用户返回了null。还有其他方法吗 我目前正在使用单例模式如何在android模块中使用全局变量,android,Android,我在库中使用了singleton来保存数据,但有时发现当用户获得singleton变量时,用户返回了null。还有其他方法吗 我目前正在使用单例模式 public class Factory { private static Factory sInstance = null; private final Config mConfig; public Factory(Config config) { mConfig = config; }
public class Factory {
private static Factory sInstance = null;
private final Config mConfig;
public Factory(Config config) {
mConfig = config;
}
public static Factory getInstance() {
return sInstance;
}
}
在线的一些用户发现以下调用将返回null
Factory.getInstance().mConfig
您可以扩展基本的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清单中,必须声明实现android.app.Application的类,并将android:name=.MyApplication属性添加到现有的应用程序标记中:
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
感谢您的回复,但我无法在应用程序中编写该方法,因为我创建了一个公共库,该库将与aar文件打包,以供公司的其他项目组使用。
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();