AsyncTask (asynchronous task)-android learning Tour (46), asynctask-android
AsyncTask: the Android UI thread mainly processes users' buttons, touch screen and View rendering, and cannot process time-consuming operations in it. Otherwise, ANR may appear, therefore, time-consuming operations must be handled by a separate thread, but the new thread cannot directly process the View of the UI thread.
How to Use AsyncTask
Sample Code
This instance only has one button and text box. click the button to download data from the network and then display it in the text box.
package peng.liu.test;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.TextView;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public class MainActivity extends Activity{ private TextView 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) throws MalformedURLException { DownTask downTask = new DownTask(this); downTask.execute(new URL("http://www.carzyit.org/ethos.php")); } class DownTask extends AsyncTask<URL,Integer,String>{ ProgressDialog dialog; int hasdata; Context context; public DownTask(Context ctx){ this.context = ctx; } @Override protected String doInBackground(URL... urls) { StringBuilder sb = new StringBuilder(); try { URLConnection conn = urls[0].openConnection(); BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8")); String line = null; while ((line = bf.readLine()) != null){ sb.append(line); hasdata++; publishProgress(hasdata); } return sb.toString(); } catch (Exception e){ e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { tvAsync.setText(s); dialog.dismiss(); } @Override protected void onPreExecute() { dialog = new ProgressDialog(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]); } }}