4
\$\begingroup\$

As I was trying to demystify the Android AsyncTask functionalities, I wrote this sample app to test it. Please review my code and suggest possible improvements:

public class AsyncTaskExampleActivity extends Activity implements OnClickListener{

    private Boolean success = true;
    private static AsyncTaskExampleActivity MainActivityInstance;
    private CallBack c;
    ProgressDialog progressDialog;
    Button startAsyncTask;
    MyAsyncTask aTask;
    Button cancelAsyncTask;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startAsyncTask = (Button)findViewById(R.id.button1);
        cancelAsyncTask = (Button)findViewById(R.id.button2);
        startAsyncTask.setOnClickListener(this);
        cancelAsyncTask.setOnClickListener(this);
        MainActivityInstance = this;

        //ProgressDialog progressDialog;
        progressDialog = new ProgressDialog(this.getApplicationContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("On Progress...");
        progressDialog.setCancelable(false);

        c = new CallBack() {
            public void onProgress(){
                //progressDialog.show();
                Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Progress!!", 1000);
                toast.show();
            }

            public void onResult(Boolean result){
                if(result.equals(true)){
                    Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Bingo...Success!!", 1000);
                    toast.show();
                }

                else {
                    Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Alas!! Failure", 1000);
                    toast.show();
                }
            }

            public void onCancel(Boolean result){
                Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Cancelled", 1000);
                toast.show();
            }
        };

        aTask = new MyAsyncTask(c);
    }   
    static AsyncTaskExampleActivity getMainActivity(){
        return MainActivityInstance;
    }

    public Boolean getSuccessOrFailureResult(){
        return success;
    }

    public void onClick(View v){
        if(v.equals(startAsyncTask)){
            aTask.execute("Start");
        }
        if(v.equals(cancelAsyncTask)){
            aTask.cancel(true);
        }
    }
}

public class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {

    private CallBack cb;
    Boolean running = true;
    MyAsyncTask(CallBack cb){

        this.cb = cb;
    }

    protected Boolean doInBackground(String... params){


            while(running){
                       if(isCancelled()){
                   break;
                     }
                try{
                    for (int i = 0; i<5; i++){
                                        if(isCancelled()){
                                    break;
                                      }
                        Thread.sleep(10000,0);
                        publishProgress();
                    }
                }
                    catch(InterruptedException e){
                        return false;
                    }           

                return true;
        }
        return false;
    }

    protected void onProgressUpdate(Integer... progress){
        cb.onProgress();
    }

    protected void onPostExecute(Boolean result){

        cb.onResult(result);

    }

    protected void onCancelled(){

        running = false;
        cb.onCancel(true);

    }

}

public interface CallBack {

    public void onProgress();
    public void onResult(Boolean result);
    public void onCancel(Boolean result);
}
\$\endgroup\$
2
  • \$\begingroup\$ Look at the newly inserted code if(isCancelled()){ break; } in the doInBackground function. This is to ensure that the background thread does not continue to process when the cancel button is pressed.. \$\endgroup\$ May 5 '14 at 15:12
  • \$\begingroup\$ Here is the link of my research on Asynctask internals.Asynctask Internals by Somenath Mukhopadhyay. Hope you like this... \$\endgroup\$ May 6 '14 at 1:38
2
\$\begingroup\$
  • If you rotate the screen, the activity will be restarted, which will restart the task as well (it might even crash because of the ProgressDialog). Eventually, I have found that only services can correctly handle long running operations. But they are more complicated to code.
  • You don't follow naming conventions from Android, and several names make no sense at all. For instance AsyncTaskExampleActivity.c should be named AsyncTaskExampleActivity.mCallback
\$\endgroup\$
1
  • \$\begingroup\$ . Your first comment is absolutely right . I understand the flaws in the naming convention. Thank you for reviewing the code.... \$\endgroup\$ May 6 '14 at 2:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.