AsyncTask has weird delay on start up of application
I have an AsynTask implementation that when I start the app from the device the app has a delay. This delay is never present on the first run, but always on the runs following the first, so if I kill the app and come back to it in say 6 minutes it will start the connection and never finish it.
Here is my AsyncTask:
private class MakeConnection extends AsyncTask<String, Void, String> {
Context context;
ProgressDialog myDialog;
public MakeConnection(Context conetext)
{
this.context = conetext;
myDialog = new ProgressDialog(this.context);
}
@Override
protected String doInBackground(String... urls) {
String response = "";
for(String url : urls)
{
try
{
URL theUrl = new URL(url);
URLConnection ucon = theUrl.openConnection();
ucon.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while(((current = bis.read()) != -1) && !isCancelled())
{
baf.append((byte)current);
}
response = new String(baf.toByteArray());
}
catch (Exception e)
{
response = e.getMessage();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
try {
myDialog.dismiss();
success(result);
}catch(JSONException e)
{
data = e.toString();
}
}
@Override
protected void onPreExecute(){
myDialog = ProgressDialog.show(
context,
"Please wait...",
"Loading the data",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
开发者_C百科 MakeConnection.this.cancel(true);
}
}
);
}
}
And then in my onCreate()
task = new MakeConnection(this);
task.execute(new String[] {url});
I cant understand why this would be happening?
EDIT:
When the app launches the first time it works nicely, but when I re open the app at a later stage the first connection seen above does the following:
- It Starts the progress dialog and then I don't know if it actually makes the connection, because all I see is the progress dialog that never goes away, in other words it never finishes the connection, because if the connection completed the progress dialog would complete
What I found was that the problem lies with the server getting the request, what I did was add a timer to refresh the connection if it took to long.
精彩评论