Android 异步任务期间关闭应用程序
我有一个使用AsyncTask的应用程序,每当我决定在它仍在运行时关闭它时,关闭过程中会有一点延迟。有没有办法解决这个问题 这是我的密码:Android 异步任务期间关闭应用程序,android,Android,我有一个使用AsyncTask的应用程序,每当我决定在它仍在运行时关闭它时,关闭过程中会有一点延迟。有没有办法解决这个问题 这是我的密码: private class GetAPI extends AsyncTask<String, Void, ArrayList<Question>> { @Override protected void onPreExecute() { super.onPreExecute(); Log
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方法吗?您可以而且应该使用提供的方法关闭异步任务。您可以将取消调用与活动的特定生命周期方法联系起来