Asynctask Introduction The Android UI thread mainly handles user keystrokes, touch screens and view rendering, and cannot handle time-consuming operations inside, otherwise the ANR will occur, so the time-consuming operation is to open a single thread, but the new thread cannot directly handle the view of the UI thread.
How to use Asynctask
code example
This instance has only one button and text box, click the button to download data from the network, and then display it in the text box.
PackagePeng.liu.test;Importandroid.app.Activity;ImportAndroid.app.ProgressDialog;ImportAndroid.content.Context;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.TextView;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLConnection; Public class mainactivity extends Activity{ PrivateTextView Tvasync;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Tvasync = (TextView) Findviewbyid (R.id.tvasync); } Public void Download(View Source)throwsmalformedurlexception {Downtask Downtask =NewDowntask ( This); Downtask.execute (NewURL ("http://www.carzyit.org/ethos.php")); } class Downtask extends asynctask<url,integer,string>{progressdialog Dialog;intHasData Context context; Public Downtask(Context CTX) { This. context = CTX; }@Override protectedStringDoinbackground(URL ... URLs) {StringBuilder SB =NewStringBuilder ();Try{URLConnection conn = urls[0].openconnection (); BufferedReader BF =NewBufferedReader (NewInputStreamReader (Conn.getinputstream (),"Utf-8")); String line =NULL; while(line = Bf.readline ())! =NULL) {sb.append (line); hasdata++; Publishprogress (HasData); }returnSb.tostring (); }Catch(Exception e) {E.printstacktrace (); }return NULL; }@Override protected void OnPostExecute(String s) {Tvasync.settext (s); Dialog.dismiss (); }@Override protected void OnPreExecute() {dialog =NewProgressDialog (context); Dialog.settitle ("Hello"); Dialog.setcancelable (false); Dialog.setmessage ("World"); Dialog.setmax (202); Dialog.setprogressstyle (progressdialog.style_horizontal); Dialog.setindeterminate (false); Dialog.show (); }@Override protected void onprogressupdate(Integer ... values) {Tvasync.settext (hasdata+""); Dialog.setprogress (values[0]); } }}
Asynctask (asynchronous Task) explaining-android learning Journey (46)