0

我有一个测验应用程序,它从 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
        }  

    }  
}
4

1 回答 1

0

SplashScreen 是一项活动吗?如果是这样,您不应该尝试保留对它的引用。

Android 在需要时销毁活动以释放内存。何时发生这种情况是不确定的,您不应干预该机制。它不使用垃圾收集器来执行此操作(它会破坏 Activity 的进程),因此如果您持有对它的引用,您将泄漏整个 Activity,这是不好的。您会在 Play 商店中看到许多具有此特定错误或其变体的应用程序。只需旋转设备 5 或 10 次,应用程序就会因内存不足而崩溃。

没有看到代码,不可能知道,但通常正确的方法是加载外部资源onResume()或稍后加载,以便无论 Activity 是新实例(例如onCreate()已被调用)还是返回前台的同一实例,它们都可用。

如果无论活动是否被销毁,您都需要保持某些状态,请将其保存(通常保存到SharedPreferences)中onPause()并检索到onResume().

于 2013-03-31T19:15:18.483 回答