ad3_auto

June 16, 2014

AsyncTask in Android.

    
       AsyncTask  is one Class which is used to perform background processes without having threads. For an AsyncTask is having 4 steps. onPreExecute, doInBackground, onProgressUpdate, onPostExecute

onPreExecute method is invoked first while calling the AsyncTask. Here comes the fuctions which are to be performed at the starting. The functions such as  showing progress dialog etc..

doInBackground method will execute after onPreExecute method. Here comes the functions which are to be done in background. The functions such as downloading files uploading files etc...

onProgressUpdate method is invoked while the progress is changed. Here we will write the code to perform the action while changing the progress.

onPostExecute method is invoked after the doInBackground method is completed. This method will execute at last. Here we will write code to perform the actions at last. The functions such as progress dialog dismiss, parse the result, redirection to another page etc..

Here is One Example:

 private class LoginProcessing extends AsyncTask<Object, Void, Void> {
         private LoginCredentials myLoginCredentials;
         private LoginToken loginToken;
         private ProgressDialog progressDialog;
      
         public LoginProcessing(LoginCredentials Credentials) {
                super();
                myLoginCredentials=Credentials;
         }

         protected void onPreExecute (){
             progressDialog = ProgressDialog.show(context, "", "Logging you in Reward World...",true);
         }
        
        @Override
        protected Void doInBackground(Object... arg0) {
            // TODO Auto-generated method stub
             try {
                   loginToken = PersistenceService.getService().login(myLoginCredentials);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return null;      
        }
        protected void onPostExecute(Void result){
            progressDialog.dismiss();
            if(loginToken!=null){
                if(loginToken.isIsValidLogin()){
                    SaveToken(loginToken.getToken());
                    Intent intent = new Intent(context, HomeScreen.class);
                    startActivity(intent);
                    finish();
                }
                else{

                     ShowLoginFailedDialog(loginToken.getErrorOnFailure().toString());                   
                }
            }else{
                Message("Service Error");
            }
              
        }
        
     }
    

In this LoginProcessing LoginCredentials is the parameters passing to the login function.The LoginProcessing AsyncTask can be called by,

            new LoginProcessing(loginCredentials).execute();


No comments:

Post a Comment