AsyncTask usage and asynchronous loading of images

 

AsyncTask: It is a lightweight asynchronous class provided by Android, which can directly inherit AsyncTask, implement asynchronous operations in the class, and provide an interface to feedback the current degree of asynchronous execution (UI progress update can be achieved through the interface), and finally feedback the execution result to UI main thread.

AsyncTask (asynchronous task), literally, is to complete some operations asynchronously while our UI main thread is running. AsyncTask allows us to execute an asynchronous task in the background. We can perform time-consuming operations in asynchronous tasks, and return the results of task execution to our UI thread at any time to update our UI controls. Through AsyncTask we can easily solve the communication problem between multiple threads.

 

4 steps: When we execute an asynchronous task, it needs to be executed according to the following 4 steps respectively

  • onPreExecute(): This method is executed before the asynchronous task is executed, and is executed in the UI Thread. Usually, we do some initialization operations of UI controls in this method, such as popping up to give ProgressDialog

  • doInBackground(Params... params): This method will be executed immediately after the onPreExecute() method is executed. This method is a method to process asynchronous tasks. The Android operating system will open a worker thread in the background thread pool to execute Our method, so this method is executed in the worker thread. After this method is executed, we can send our execution result to our last onPostExecute method. In this method, we can obtain data from the network, etc. some time-consuming operations

  • onProgressUpdate(Progess... values): This method is also executed in the UI Thread. When we execute asynchronous tasks, sometimes we need to return the progress of the execution to our UI interface. For example, to download a network image, we need to Display the progress of its download at all times, you can use this method to update our progress. Before calling this method, we need to call a publishProgress(Progress) method in the doInBackground method to pass our progress to the onProgressUpdate method to update

  • onPostExecute(Result... result): When our asynchronous task is executed, the result will be returned to this method. This method is also called in the UI Thread. We can display the returned result on the UI control.

A super simple example of understanding AsyncTask: AsyncTask to download a picture from the network

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageViewss"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:src="@drawable/ic_launcher"
        android:scaleType="fitCenter"/>
 
    <Button
        android:id="@+id/buttonOnClicksAsyncTask"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200dp"
android:text="Download a picture from the Internet" />
</RelativeLayout>

 Activity code:

private Button btn;
private ImageViewimageView;
privateProgressDialog progressDialog;
private final String IMGURL= "http://img0.pconline.com.cn/pconline/1206/18/2829090_3867bd63fd673471aa184c02_500.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.asynctask_img);
        btn=(Button)findViewById(R.id.buttonOnClicksAsyncTask);
        imageView =(ImageView)findViewById(R.id.imageViewss);
        progressDialog = newProgressDialog(this);
        progressDialog.setTitle("Prompt information");
        progressDialog.setMessage("Downloading, please wait...");
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        btn.setOnClickListener(newView.OnClickListener()
        {
            @Override
            public voidonClick(View v)
            {
            // Instantiate the AsyncTask object in UI Thread and call the execute method
                newMAsyncTask (). execute (IMGURL);
            }
        });
    }

 public class MAsyncTask extends AsyncTask<String, Integer, byte[]>
    {
        @Override
        protected voidonPreExecute()
        {
            super.onPreExecute();
            progressDialog.show();
        }
        @Override
        protected byte[]doInBackground(String... params)
        {
            HttpClient httpClient = newDefaultHttpClient();
            HttpGet httpGet = newHttpGet(params[0]);
            byte[] image =new byte[]{};
            try
            {
                HttpResponse httpResponse =httpClient.execute(httpGet);
                HttpEntity httpEntity =httpResponse.getEntity();
                if(httpEntity!= null &&httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                {
                    image = EntityUtils.toByteArray(httpEntity);
                }
            }
            catch(Exception e)
            {
                e.printStackTrace ();
            }
            finally
            {
               httpClient.getConnectionManager().shutdown();
            }
            return image;
        }
        @Override
        protected voidonProgressUpdate(Integer... values)
        {
            super.onProgressUpdate(values);
        }
        @Override
        protected voidonPostExecute(byte[] result)
        {
            super.onPostExecute(result);
            // Decode the byte[] returned by the doInBackground method into Bitmap
            Bitmap bitmap = BitmapFactory.decodeByteArray(result,0, result.length);
            // Update our ImageView control
            imageView.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }
    }
}

 

An ImageView control and a Button control. When the Button control is clicked, a ProgressDialog pops up, and then an asynchronous task is started to download an image from the network and update it to our ImageView. It should also be noted here that if we want to access the network, we must also authorize it.

AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
         >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 </application>

 

Effect picture:

 

 

 Source code click to download

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326371232&siteId=291194637