Fechang Fuchang
Fechang Fuchang

Reputation: 151

How to stop an asynchronus task midway

I have an Async task:

private class UpdateApp extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String result = "";

        try{
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(),0);
            curVersionCode = packageInfo.versionCode;
        } catch (Exception Ignored) {

        }
        result = check(curVersionCode);
        return result;
    }

 ...


  @Override
    protected void onPostExecute(final String success){
        if (success != "a") this.cancel(true); //Here's the confusion
        switch (success){
            case "z":
                new AlertDialog.Builder(mContext).setMessage("0").setCancelable(true).show();
                break;
            case "a":
                new AlertDialog.Builder(mContext).setMessage("1").setCancelable(true).show();
                break;
            default:new AlertDialog.Builder(mContext).setMessage("default").setCancelable(true).show();
                break;
        }
    }

I want to stop the Asynctask if success is !=a. How to achieve that?

It is possible to let it continue and switch through only if success == a and break otherwise. What will be best - let it continue or cancel the task midway?

Upvotes: 1

Views: 61

Answers (2)

Jay Thummar
Jay Thummar

Reputation: 2299

One can use OBJECT_OF_ASYNK_TASK.cancel(); In Android Studio explanation of this method is give check that for more information

 class Temp extends AsyncTask<Void,Void,Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }
}

private void runTemp(){
    Temp temp =   new Temp();
    temp.execute();
    temp.cancel(true);
}

Upvotes: 0

greenapps
greenapps

Reputation: 11224

If the code in onPostExecute() runs than doInBackground is finished().

So the AsyncTask has stopped then.

It does not have to be cancelled anymore.

Does not make sense.

Upvotes: 1

Related Questions