我正在开发一个Android应用程序,它从我创建的只包含几个属性的文件中读取一些属性。从MainActivity调用onCreate()
方法时,将使用从文件中获取的属性加载属性并设置一些全局变量。
问题是,在干净安装后应用程序启动时,将忽略这些属性,并且不设置任何值。如果我退出应用程序并再次运行它,则所有值都已正确设置。
我怀疑onCreate()
方法运行并请求属性比应用程序有时间设置它们更快。在第二次发布时,这些属性来自上一次运行。
该应用程序使用地图,并在干净安装后发生同样的问题:没有显示位置,但重新启动应用程序(无卸载)后,地图显示正确,属性也是如此。
代码看起来像这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
requestPermissions();
initializeMap();
loadConfigurations();
addListenersToButtons();
PropertyManager.createPropertyFileIfNotPresent();
PropertyManager.readProperties();
}
和PropertyManager方法:
public static void createPropertyFileIfNotPresent() {
File file = new File(Environment.getExternalStorageDirectory() + PROPERTY_PATH);
if (!file.exists()) {
Properties prop = new Properties();
OutputStream output = null;
try {
final String path = Environment.getExternalStorageDirectory() + PROPERTY_PATH;
output = new FileOutputStream(path);
prop.setProperty("property1", "1234");
prop.setProperty("property2", "5678");
prop.setProperty("property3", "60");
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
closeStream(output);
}
}
}
public static void readProperties() {
Properties prop = new Properties();
InputStream input = null;
try {
final String path = Environment.getExternalStorageDirectory() + PROPERTY_PATH;
input = new FileInputStream(path);
prop.load(input);
GlobalData.getInstance().property1 = prop.getProperty("property1");
GlobalData.getInstance().property2 = prop.getProperty("property2");
GlobalData.getInstance().property3 = prop.getProperty("property3");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
closeStream(input);
}
}
有关如何在干净安装后确保设置所有属性的任何建议,而不在启动时使用加载页面?
感谢您的时间。
答案 0 :(得分:0)
我弄清楚是什么导致了这个问题。 我在原帖中怀疑,结果证实是真的。 - “我怀疑onCreate()方法运行并且比应用程序有时间设置它们更快地请求属性。”
我解决此问题的方法是覆盖以下方法,并且只有在调用时才创建映射并运行需要属性的代码:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// do the work that needs the permissions here
}
感谢您的建议