简体   繁体   中英

How properly handle AsyncTask cancelling in Android?

I implemented AsyncTask in my app to properly download file from internet and put data in my local DB. File is downloading and everything works. I also check if there is internet connection, and if there is no any, i am returning 0 in my doInBackground method, what is causing my AsyncTask calling "onPostExecute" method, and everything goes as it should. But I saw that if internet connection is poor, for instance I am at the edge of my WiFi range, AsyncTask sometimes downloads file for minutes. This is not what I want. So I implemented im my AsyncTask, in onPreExecute method Handler.

isFreezed = new Handler();
isFreezed.postDelayed(new Runnable() {
    @Override
    public void run() {
        if (!isCancelled() && getStatus() != AsyncTask.Status.FINISHED){
            cancel(true);
            //Log.i("callingActivity", "Zbyt wolne połączenie, anulowanie.");
            onPostExecute((long) 0);
        }
    }
},8000);

I am cancelling my AsyncTask. I saw that when I cancel it, onPostExecute method is not executed, so I call it manually. And that's what is my problem, google says that it should not be called manually. Is my way of thinking good and putting handler to cancel task and go on with my app is a good practice, or should I do it other way? And am I right that when I will cancel AsyncTask, it's onPostExecute method won't be called?

For that you can use Async task like

private class  AsyncTaskDemo extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(true);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance

         // do stuff according to your need
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();
        Toast toast = Toast.makeText(MainActivity.this,
                "Error connecting to Server", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM