我在片段的 onCreateView 中执行了一个异步任务。当屏幕关闭并且应该以某种方式显示片段时,异步任务启动但 isCancelled() 为真。我使用了 PARTIAL_WAKE_LOCK 但问题没有解决。提前致谢。
这是一个示例代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = getSherlockActivity();
context = activity.getApplicationContext();
view = inflater.inflate(R.layout.main, container, false);
DownloadXMLTask = new DownloadXML(getActivity());
DownloadXMLTask.execute(file);
return view;
}
private class DownloadXML extends AsyncTask<File, Integer, String> {
private Activity activity;
public DownloadXML(Activity activity) {
this.activity = activity;
}
protected void onPreExecute() {
... Do stuff ...
}
protected String doInBackground(File... files) {
// Check if the task is cancelled
if (isCancelled()) { return null; }
... Do stuff ...
... Do stuff ...
... Do stuff ...
return null;
}
protected void onPostExecute(String result) {
... Do stuff ...
}
@Override
protected void onCancelled() {
... Do stuff ...
}
}