我在片段中的onCreateView中執行了一個asynctask。當屏幕關閉並以某種方式顯示片段時,asynctask開始,但isCancelled()爲true。我用PARTIAL_WAKE_LOCK,但問題沒有解決。 在此先感謝。Android AsyncTask在屏幕關閉時執行isCancelled()= true
這裏是一個示例代碼
@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 ...
}
}
你已經描述了行爲是什麼,但不是你想要的行爲。 –
感謝您的評論。當屏幕開啓時,我需要按預期執行任務。只有當用戶取消時才應該取消。 – adamioan
@adamioan:當「屏幕關閉」時,你的Activity和任何Fragments將不再處於運行狀態。如果你想做後臺處理,比如下載,那麼使用'Service'。 – Squonk