我有一个从plist文件加载问题数据库的测验应用程序。当应用程序刚刚加载时,它会运行一个线程来加载问题文件。
一段时间后,当你再次打开应用程序并尝试运行一个新的测验时,它没有加载任何问题。
我想象它是某种垃圾收集器,操作系统使用它来清理一些内存,它正在做它的工作,所以这是好的。
但是你推荐用什么方法重新加载文件呢?我想重写savedInstanceState?
这是启动屏幕和加载程序的组合,是第一个运行
的活动public class SplashScreen extends Activity {
/** Called when the activity is first created. **/
ProgressDialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new LoadViewTask().execute();
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>{
//Before running code in separate thread
@Override
protected void onPreExecute(){
dialog = new ProgressDialog(SplashScreen.this);
dialog.setMessage("Loading...");
dialog.setTitle("Loading File");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
//The code to be executed in a background thread.
@Override
protected Void doInBackground(Void... params){
try{
//Get the current thread's token
synchronized (this){
QuestionsLoader.getInstance(SplashScreen.this);
}
}
catch (Exception e){
e.printStackTrace();
Log.d("TAG", "exception" + e);
}
return null;
}
//Update the progress
@Override
protected void onProgressUpdate(Integer... values){
}
//after executing the code in the thread
@Override
protected void onPostExecute(Void result){
dialog.dismiss();
Intent i = new Intent("com.project.AnActivity");
startActivity(i);
finish(); //Finish the splash screen
}
}
}
SplashScreen是一个活动吗?如果是这样,就不应该试图保留对它的引用。
Android在需要时销毁活动以释放内存。这种情况何时发生是不确定的,你不应该干涉这种机制。它不使用垃圾收集器来做这件事(它会破坏Activity的进程),所以如果你持有对它的引用,你会泄漏整个Activity,这是不好的。你可以在Play Store上看到许多应用程序都有这个特定的漏洞,或者它的变体。只要旋转设备5到10次,应用程序就会因为内存不足而崩溃。
没有看到代码,这是不可能知道的,但通常正确的方法是加载外部资源在onResume()
或以后,这样他们是可用的活动是一个新的实例(例如onCreate()
已被调用)或相同的实例返回到前台。
如果无论活动是否被破坏,都需要保留某些状态,请将其保存在onPause()
中(通常保存到SharedPreferences
),并在onResume()
中检索。