Thursday 29 October 2015

AsyncTask

AsyncTask

  • AsyncTask enables proper and easy use of the UI thread. 
  • This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
  •  AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. 
  • If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs.

  • An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. 
  • An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Usage:

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)



 Example coding:

public class MainActivity extends AppCompatActivity {

    Button download; ImageView iv;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        download=(Button)findViewById(R.id.button);

        iv=(ImageView)findViewById(R.id.imageView);

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement

        if (id == R.id.action_settings) {

            return true;

        }

        return super.onOptionsItemSelected(item);

    }

    public void go(View v){

        Downloadimage dli=new Downloadimage(MainActivity.this,iv);

        dli.execute("http://de.wallpapersma.com/wp-

                 content/uploads/2013/05/Cute-Baby-im-Herbst.jpg");

    }

}



public class Downloadimage extends AsyncTask<String,String,Bitmap> {

    ProgressDialog pd;

    Context c;

    ImageView img;

    public Downloadimage( Context c, ImageView img) {

       // this.pd = pd;

        this.c = c;

        this.img = img;

    }

    @Override

    protected Bitmap doInBackground(String... params) {

        Bitmap b=null;

        try {

            b = BitmapFactory.decodeStream((InputStream) new

                URL(params[0]).getContent());

        }catch (Exception e){

           

        }

        return b;

    }

    @Override

    protected void onPreExecute() {

        super.onPreExecute();

        pd=new ProgressDialog(c);

        pd.setMessage("Loading image");

        pd.show();

    }

    @Override

    protected void onPostExecute(Bitmap bitmap) {

        super.onPostExecute(bitmap);

        pd.dismiss();

        img.setImageBitmap(bitmap);

    }

}


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.retro.karthik.asyncimagedownkarapp" >

<uses-permission

android:name="android.permission.INTERNET"></uses-permission>

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <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>

</manifest>


AsyncTask's generic types:

 

The three types used by an asynchronous task are the following:
  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.
To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }


The 4 steps:

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2.  doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Threading rules:

There are a few threading rules that must be followed for this class to work properly:

 



 

 


 

0 comments:

Post a Comment