我有一个使用AsyncTask
的应用程序,每当我决定在它仍在运行时关闭它时,结束时会有轻微的延迟。有什么办法可以解决吗?
这是我的代码:
private class GetAPI extends AsyncTask<String, Void, ArrayList<Question>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("QA", "Begin GETAPI");
}
@Override
protected ArrayList<Question> doInBackground(String... urls) {
InputStream inputStream;
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(urls[0]));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
questions = new ArrayList<>();
// convert inputstream to string
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
Log.i("QA", "Retrieved question " + i);
questions.add(new Question(jo.getString("questionText"), jo.getInt
("magnetid"), "", jo.getInt("personid"), jo.getInt("id")));
questions.get(i).setId(jo.getInt("id"));
}
}
} else
throw new InputMismatchException("Didn't work");
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return questions;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(ArrayList<Question> strings) {
super.onPostExecute(strings);
Log.i("QA", "End GETAPI");
QuestionAdapter questionAdapter = new QuestionAdapter(questions);
recyclerView.setAdapter(questionAdapter);
refreshContent(false);
}
}
我不太明白为什么在最近的应用程序屏幕中运行AsyncTask
并关闭此应用程序时,它会导致手机延迟。是因为我没有覆盖onCancel()
方法吗?
答案 0 :(得分:0)
您可以(并且应该)使用提供的方法关闭AsyncTask。您可以将取消调用绑定到Activity的特定生命周期方法。