1

我正在制作一个包含onCreateMainActivity的 Android 应用程序,检查它是否必须下载文件。检查发生在AsynchTask类中。我有第二个活动启动一个偏好。PrefsActivityPrefsfragment

现在,当我从 回来时PrefsActivity, 再次发出onCreate 。但整个检查不必再次发生。

导致偏好的代码

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.preferences:
            Intent intent = new Intent(this, PrefsActivity.class);
            startActivityForResult(intent, 1);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

偏好代码

public class PrefsActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
}
}

在 MainActivity 中启动 Asynchtask 的代码

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PropertiesManager.getUniqueInstance().loadProperties(PropertiesManager.PROPERTIES_FILE, this);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean auto_update = sharedPreferences.getBoolean("pref_autoUpdate", true);
    File downloadFile = getExternalFilesDir("media/" + Downloader.DOWNLOAD_FILE_NAME);

    if (auto_update || !downloadFile.exists()) {
        try {
            if (new Downloader(this).execute().get()) {
                receiveBroadcast(this);
            } else {
                schedule = Parser.getUniqueInstance().parse(this);
                ScheduleBuilder.getUniqueInstance().build(this, (DayBean) schedule.get(9));
            }
        } catch (InterruptedException ex) {
            Log.e(TAG, ex.getMessage());
        } catch (ExecutionException ex) {
            Log.e(TAG, ex.getMessage());
        }
    } else {
        schedule = Parser.getUniqueInstance().parse(this);
        ScheduleBuilder.getUniqueInstance().build(this, (DayBean) schedule.get(9));
    }
}
4

1 回答 1

0

在第一个活动中,仅当savedInstance捆绑包为空时才创建 AsyncTask。这意味着由于配置更改或用户导航回它(您的情况),不会重新创建活动。就像是:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(savedInstanceState == null) {
        //instantiate the AsyncTask and execute it 
    }
}
于 2013-09-10T13:17:00.850 回答