Reputation: 65
This question was asked and answered some time ago link. However the answer did not help me yet. I am in sort of the same position as the OP of the other post: I have an Asynctask in which I make a connection to a certain website, however, most of the time the connection will take some time due to a laggy internetconnection. I want the user to be able to stop trying to connect at any time.
public class DownloadWebHtml extends AsyncTask<String, Void, Map<String,ArrayList<ArrayList<String>>>> {
HttpURLConnection con = null;
@Override
protected void onPreExecute(){
Button but = (Button) findViewById(301);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancel(true);
con.disconnect();
}
});
}
@Override
protected Map<String, ArrayList<ArrayList<String>>> doInBackground(String... urlcodes) {
//stuff
BufferedReader in = null;
try {
URL url = new URL("some url");
con = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(con.getInputStream(),Charset.forName("ISO-8859-1")));
String line = "";
while ((line = in.readLine()) != null && !isCancelled()) {
html.add(line);
}
in.close();
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
} finally {
con.disconnect();
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.d("gettxt", e.getMessage());
}
}
}
if(!html.isEmpty()) {
return //stuff;
}
return null;
}
@Override
protected void onCancelled(){
//cancellation
}
//onpostexecute doing stuff
}
Whenever the button is pressed the whole AsyncTask will by cancelled only after a connection has been made. Is it possible to immediately stop the whole process on a button press? Can it be done using the default httpurlconnection?
I tried using the disconnect to trigger an exception while the con.getInputStream
is busy, but it failed to work.
Upvotes: 3
Views: 2407
Reputation: 14274
I recommend switching to Apache's HTTP Components. It works a charm, and has a thread-safe abort
method, as outlined here.
Upvotes: 1