Android Network Programming HttpUrlConnection HttpClient AsyncTask, androidasynctask
The previous articles introduced volley, a common http framework in Android, which encapsulates a series of operations we need and simplifies our work.
However, we still need to master the native Network Operation classes of Android, so this article mainly introduces these two classes,
HTTPUrlConnection HTTPClientAnd frequently usedAsyncTask.
Github address: UseAsyncTask
1. HttpUrlConnection
A UrlConnection is often used to send and obtain data over the network. data can be of any type of length,HttpUrlConnectionIt is usually used to send and receive stream data with unknown length;
A simple example of using HttpUrlConnection: retrieving images remotely and displaying them in ImageView
ImageView imageView = (ImageView ). findViewById (R. id. imageview); URL url = new URL (http://www.jycoder.com/json/movies/1.jpg); HttpUrlConnection conn = (HttpUrlConnection) url. openConnection (); conn. connect (); try {InputStream in = conn. getInputStream (); // display the obtained image in ImageView Bitmap bitmap = BitmapFactory. decodeStream (in); imageView. setImageBitmap (BitmapFactory. decode (is);} finally {conn. disconnect ();}
The above is the basic usage of HttpUrlConnection, and some theme to be mastered:
2, HttpClient
Android has been deprecated since API 22. Use HttpUrlConnection whenever possible.
3. AsyncTask
AsyncTask is a mechanism for implementing asynchronous operations. We often need to update the UI, but the main thread cannot perform time-consuming operations. Otherwise, an error occurs. AsyncTask is used to perform background operations, no need to manually process the creation and execution of threads; it is often used to process someShort-term operationsIf you want to use the Service for a long time
Use AsyncTask:
We also need to override the four methods in AsyncTask:
Tips: we can see that the four methods in AsyncTask only run in the doInBackground () real background thread. Therefore, some time-consuming operations are executed in it, while other methods run in the UI thread, update the UI view.
Execute a Task in the main thread: AsyncTask must be instantiated and executed in the main thread, and each AsyncTask must be executed only once.
Cancel a Task: AsyncTask can be canceled at any time by calling cancel (true.
Based on the above, let's do an exercise:
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <TextView android: text = "Top10" android: background = "#1C9439" android: textSize = "24sp" android: textColor = "# fff" android: layout_marginTop = "5dp" android: layout_marginBottom = "10dp" android: gravity = "center" android: layout_marginLeft = "10dp" android: layout_marginRight = "10dp" android: layout_width = "match_parent" android: layout_height = "wrap_content"/> <ImageView android: id = "@ + id/movie_image" android: layout_gravity = "center" android: background = "# ffcc" android: layout_margin = "3dp" android: layout_width = "wrap_content" android: layout_height = "wrap_content"/> </LinearLayout>
Public class MainActivity extends ActionBarActivity {private ImageView imageView; // picture address private final String url = "http://www.jycoder.com/json/movies/2.jpg"; // display progress private ProgressDialog pDialog; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // used to display the progress pDialog = new ProgressDialog (this); pDialog. setProgressSt Yle (ProgressDialog. STYLE_HORIZONTAL); pDialog. setMessage ("Loading... "); pDialog. setMax (100); imageView = (ImageView) findViewById (R. id. movie_image); // execute Task new imagedownloadtask(cmd.exe cute (url);} public class ImageDownloadTask extends AsyncTask <String, Integer, Bitmap >{@ Override protected void onPreExecute () {super. onPreExecute (); pDialog. show () ;}@ Override protected Bitmap doInBackground (String... Urls) {HttpURLConnection connection = null; Bitmap bitmap = null; try {URL url = new URL (urls [0]); connection = (HttpURLConnection) url. openConnection (); InputStream in = new BufferedInputStream (connection. getInputStream (); bitmap = BitmapFactory. decodeStream (in); // get the file stream size, used to update the progress int length = connection. getContentLength (); int len = 0, total_length = 0, value = 0; byte [] data = new byte [1024]; while (len = I N. read (data ))! =-1) {total_length + = len; value = (int) (total_length/(float) length) * 100); // call the update function, update Progress publishProgress (value) ;}} catch (IOException e) {e. printStackTrace ();} finally {if (connection! = Null) connection. disconnect () ;}return bitmap ;}@ Override protected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); pDialog. setProgress (values [0]);} @ Override protected void onPostExecute (Bitmap bitmap) {if (pDialog! = Null) pDialog. dismiss (); pDialog = null; // fill the Bitmap in the Imageview imageView. setImageBitmap (bitmap );}}}
Summary:
This part is simple ~, In fact, it is difficult to understand the UI thread and the application scenarios of AsyncTask and Service.
Reference: Android AsyncTask