Skip to content Skip to sidebar Skip to footer

How To Make Asynctask Modular In Android

I am quite new to Android Development. I am working in a app where i need to make a lot of async calls to api. For each and every API call, I have to write the similar looking Asyn

Solution 1:

yes it is possible use Listener and AsyncTask with parameterized constructor

Check it

Create an interface

publicinterfaceOnTaskCompletListerner {
 voidoncompleteListerner(String name);
}

create an AsyncTask class as follows

publicclassAsyncTaskModulerextendsAsyncTask<Void, Void, String> {

    privateContext context;
    privateHashMap<String, String> data;
    privateStringURL;
    privateOnTaskCompletListerner taskdone;

    publicAsyncTaskModuler(Context ctx,HashMap<String, String> data,String url,OnTaskCompletListerner taskdone){

        this.context=ctx;
        this.data=data;
        this.URL=url;
        this.taskdone=taskdone;
    }

    @OverrideprotectedStringdoInBackground(Void... params) {
        //Do the task here and return the value if needed returnnull;
    }

    @OverrideprotectedvoidonPostExecute(String result) {
        taskdone.oncompleteListerner(result);
    }

and call it in your activity like this

publicclassCallAyncextendsActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url="";
        HashMap<String, String> data=newHashMap<String, String>();
        AsyncTaskModuler moduler=newAsyncTaskModuler(CallAync.this, data, url, completListerner);
        moduler.execute();
    }

    OnTaskCompletListerner completListerner=newOnTaskCompletListerner() {

        @OverridepublicvoidoncompleteListerner(String name) {

        }
    };
}

Solution 2:

Create an general async task and pass your url as param to it .Hence you can reuse the same async task for all your api calls

publicclassmyTaskextendsAsyncTask<Void, Void, Void> {

    String muUrl;   


    publicmyTask(Context context, Activity activity,
            String url) {
        contxt = context;
        myUrl=url;
    }

    @OverrideprotectedVoiddoInBackground(Void... params) {

        makeApiCalls();

        returnnull;
    }
}

Start the task in the following way :

new myTask(this, this, urlStr).execute();

EDIT

How can I perform different logic onPostExecute() ?

You can add another param in the constructor of myTask. Ex.

public MyTask(Context context, Activity activity,
                    String url,String postExecuteAction) {
}

In your post executes just check of each case in if else and perform the respective task

Solution 3:

Dummy Background class

privateclassBackGroundClassextendsAsyncTask<String, Void, Bitmap> //<arg to do InBackground,,returntype of do inBackground and arg of onPostExecut>
   
{

 publicBackGroundClass()
    {

    }

 @OverrideprotectedvoidonPreExecute()//forground work in UI thread prior to doInbackground
    {
        super.onPreExecute();
      
    }

    @Overrideprotected Bitmap doInBackground(String... urls)//background work in parallel thread
    {
        Bitmap b=null;
       // your background workreturn b;
    }

    @OverrideprotectedvoidonPostExecute(Bitmap result)//forground work in UI thread post to doInbackground
    {
        super.onPostExecute(result);
        if(result!=null)
        {               
            //use bitmap image in result    
        }
       else
       {   
          //Image is not available
       }    

    }

  }

Calling for one parellel execution

new BackGroundClass().execute(StringArg1,stringArg2,StringArg3);

Calling for multiple parellel execution

when tou need to call more than one background task at same time

new BackGroundClass().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,StringArg1,stringArg2,StringArg3);

Called from single activity

use this as an inner class to your activity for making it easy to share variable if not called from more than one activity

Called from more than one activity

use constructor to pass activity context,and other variable

new BackGroundClass(constructor arguments).execute(StringArg1,stringArg2,StringArg3);

  new BackGroundClass(constructor arguments).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,StringArg1,stringArg2,StringArg3);

Post a Comment for "How To Make Asynctask Modular In Android"