SoFunction
Updated on 2025-04-10

Detailed explanation of the usage of asynctask


package ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class NetworkActivity extends Activity{
private TextView message;
private Button open;
private EditText url;

@Override
public void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView();
message= (TextView) findViewById();
url= (EditText) findViewById();
open= (Button) findViewById();
(new () {
public void onClick(View arg0) {
connect();
}
});

}

private void connect() {
PageTask task = new PageTask(this);
(().toString());
}


class PageTask extends AsyncTask<String, Integer, String> {
// Variable length input parameters, corresponding to ()
ProgressDialog pdialog;
public PageTask(Context context){
pdialog = new ProgressDialog(context, 0);
("cancel", new () {
public void onClick(DialogInterface dialog, int i) {
();
}
});
(new () {
public void onCancel(DialogInterface dialog) {
finish();
}
});
(true);
(100);
(ProgressDialog.STYLE_HORIZONTAL);
();


}
@Override
protected String doInBackground(String... params) {

try{

HttpClient client = new DefaultHttpClient();
// params[0] represents the connected url
HttpGet get = new HttpGet(params[0]);
HttpResponse response = (get);
HttpEntity entity = ();
long length = ();
InputStream is = ();
String s = null;
if(is != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buf = new byte[128];

int ch = -1;

int count = 0;

while((ch = (buf)) != -1) {

(buf, 0, ch);

count += ch;

if(length > 0) {
// If you know the length of the response, call publishProgress() to update the progress
publishProgress((int) ((count / (float) length) * 100));
}

// Let the thread sleep for 100ms
(100);
}
s = new String(()); }
// Return result
return s;
} catch(Exception e) {
();

}

return null;

}

@Override
protected void onCancelled() {
();
}

@Override
protected void onPostExecute(String result) {
// Return the content of the HTML page
(result);
();
}

@Override
protected void onPreExecute() {
// The task is started, a dialog box can be displayed here, and it is simple to handle it here
(.task_started);
}

@Override
protected void onProgressUpdate(Integer... values) {
// Update progress
(""+values[0]);
(""+values[0]);
(values[0]);
}

}

}