Android 到处传递上下文
Android passing Context everywhere
我开发了一个 Android 应用程序,但(对我来说)它太丑了,我很确定我的方法是错误的。
我有一堆片段活动和很多 classes,比如异步任务、业务规则等等。特别是,我有一个名为 PropertiesReader 的 class,我用它来读取属性文件。我在很多地方使用这个 class,比如片段和业务规则。
public class PropertyReader {
private Properties properties;
public PropertyReader(Context context){
super();
try {
properties = new Properties();
properties.load(context.getResources().getAssets().open("badass.properties"));
} catch (IOException e){
Log.e("Error", "Error opening properties file", e);
}
}
public String getValue(String key){
return properties.getProperty(key);
}
}
在我使用这个 class 的每个地方,我都会做类似的事情:
PropertyReader bla = new PropertyReader(this); //or new PropertyReader(context);
我想知道使用需要构建上下文的 classes 的最佳方法是什么。在我看来,每个构造函数都有一个上下文参数是非常丑陋的。
有什么想法吗?
提前致谢。
创建单例,并在创建时保存应用程序上下文。
看起来像这样:
public class PropertyReader {
private static PropertyReader ourInstance = new PropertyReader();
private Context mContext;
public static PropertyReader getInstance() {
return ourInstance;
}
private PropertyReader() {
}
public void loadProperties(Context context) {
mContext = context;
try {
properties = new Properties();
properties.load(context.getResources().getAssets().open("badass.properties"));
} catch (IOException e){
Log.e("Error", "Error opening properties file", e);
}
}
}
当您的应用程序启动时,您可以执行以下操作:
PropertyReader.getInstance().loadProperties(getApplicationContext());
然后您就可以在其他任何地方访问您的 PropertyReader:
PropertyReader.getInstance().getValue(key);
我开发了一个 Android 应用程序,但(对我来说)它太丑了,我很确定我的方法是错误的。
我有一堆片段活动和很多 classes,比如异步任务、业务规则等等。特别是,我有一个名为 PropertiesReader 的 class,我用它来读取属性文件。我在很多地方使用这个 class,比如片段和业务规则。
public class PropertyReader {
private Properties properties;
public PropertyReader(Context context){
super();
try {
properties = new Properties();
properties.load(context.getResources().getAssets().open("badass.properties"));
} catch (IOException e){
Log.e("Error", "Error opening properties file", e);
}
}
public String getValue(String key){
return properties.getProperty(key);
}
}
在我使用这个 class 的每个地方,我都会做类似的事情:
PropertyReader bla = new PropertyReader(this); //or new PropertyReader(context);
我想知道使用需要构建上下文的 classes 的最佳方法是什么。在我看来,每个构造函数都有一个上下文参数是非常丑陋的。
有什么想法吗?
提前致谢。
创建单例,并在创建时保存应用程序上下文。
看起来像这样:
public class PropertyReader {
private static PropertyReader ourInstance = new PropertyReader();
private Context mContext;
public static PropertyReader getInstance() {
return ourInstance;
}
private PropertyReader() {
}
public void loadProperties(Context context) {
mContext = context;
try {
properties = new Properties();
properties.load(context.getResources().getAssets().open("badass.properties"));
} catch (IOException e){
Log.e("Error", "Error opening properties file", e);
}
}
}
当您的应用程序启动时,您可以执行以下操作:
PropertyReader.getInstance().loadProperties(getApplicationContext());
然后您就可以在其他任何地方访问您的 PropertyReader:
PropertyReader.getInstance().getValue(key);