我使用本文中描述的方法,在Fragment 的 AsyncTask 中下载和解析 html 页面。在模拟器上一切正常,但后来我在我的 Galaxy S2 上试了一下。当我旋转我的设备时,listview 不会刷新,如果我将设备旋转回来,它会刷新。
这是我如何在 onCreate 中使用我的片段的代码(LinksDownloader - 用于解析 html 的类)
FragmentManager fm = getSupportFragmentManager();
mTaskFragment = (DownloadLinksTaskFragment) fm.findFragmentByTag("task");
if (mTaskFragment == null){
mTaskFragment = new DownloadLinksTaskFragment();
mTaskFragment.linksDownloader = new LinksDownloader();
fm.beginTransaction().add(mTaskFragment, "task").commit();
}
...
goButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mTaskFragment.execute();
}
});
...
linksAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, mTaskFragment.linksDownloader.linksArray);
linksListView.setAdapter(linksAdapter);
和片段类
public class DownloadLinksTaskFragment extends Fragment {
static interface TaskCallbacks {
void onPreExecute();
void onPostExecute(Byte mssg);
}
private TaskCallbacks mCallbacks;
private DownloadLinksTask mTask;
public LinksDownloader linksDownloader;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (TaskCallbacks) activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
public void execute() {
mTask = new DownloadLinksTask();
mTask.execute();
}
private class DownloadLinksTask extends AsyncTask<Void, Void, Byte> {
@Override
protected void onPreExecute() {
if (mCallbacks != null) {
mCallbacks.onPreExecute();
}
}
@Override
protected void onPostExecute(Byte b) {
if (mCallbacks != null) {
mCallbacks.onPostExecute(b);
}
}
@Override
protected Byte doInBackground(Void... v) {
byte exceptionType = 0;
try {
linksDownloader.download();
} catch (HttpStatusException e) {
exceptionType = 1;
} catch (WrongContentException e) {
exceptionType = 2;
} catch (ConnectTimeoutException e) {
exceptionType = 3;
} catch (SocketTimeoutException e) {
exceptionType = 3;
} catch (UnknownHostException e) {
exceptionType = 3;
} catch (IOException e) {
exceptionType = 4;
} catch (Exception e) {
exceptionType = 5;
}
return exceptionType;
}
}
}