Reputation: 445
I have a button that performs an AsyncTask
HTTP Get request. However, multiple rapid presses of this button often freeze the button UI in the pressed state (it uses an XML selector
) and I'm not sure why. I thought AsyncTasks didn't affect the UI. Can someone please provide insight as to why the button freezes up sometimes?
I've tried execute
and executeOnExecutor
with no difference.
The onClickListener
:
iv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (buttonEvent > 0) {
String url = "bogusurl" + buttonEvent.toString();
System.out.println(url);
try {
HTTPRequest request = new HTTPRequest();
//request.execute(url).get();
request.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url).get();
} catch (Exception e) {
e.printStackTrace();
}
}
if (jumpPage > 0) {
loadPage(jumpPage);
}
}
});
And the AsyncTask Class itself:
public class HTTPRequest extends AsyncTask<String, Void, Void> {
private static final int CONNECTION_TIMEOUT = 3000;
@Override
protected Void doInBackground(String... params) {
String stringUrl = params[0];
URL myUrl;
HttpURLConnection connection = null;
try {
myUrl = new URL(stringUrl);
connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(CONNECTION_TIMEOUT);
Log.d("Request", "Sending command");
connection.connect();
InputStream in = connection.getInputStream();
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
}
Upvotes: 0
Views: 46
Reputation: 2121
As mentioned in the AsyncTask documentation,
get()
method will wait if it is necessary for the computation to complete, and then retrieves its result.
Remove get()
method. Because of it, your main thread is waiting for the response from the background task.
If you want to process the result of your AsyncTask class, then it is better you override onPostExecute(Result result)
. It runs after doInBackground(Params... params)
with the result.
Upvotes: 1