取消AsyncTask时不显示AlertDialog

时间:2016-01-16 08:55:02

标签: android android-asynctask alertdialog

取消AsyncTask时出现了一些问题,AsyncTask位于处理某些数据的 Fragment 中。如果互联网会话过期,则应取消 AsyncTask并显示一个对话框以通知用户。

但是,如果我取消AsyncTask,则会显示的AlertDialog,我也注意到onPostExecute() 被调用,但try是仍然执行。

如果有人请帮助?

编辑:如果我使用while方法,则会显示AlertDialog,但如何正确取消AsyncTask,因为doInBackground()while (!isCancelled()) { // Do stuff } 的代码仍然存在执行?

public class Tb3_Abonnement extends Fragment {

    private AsyncTask<Void, Void, Void> task;
...
@Override // If Fragment is visible to user, start asynctask
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
                // execute AsyncTask
                startFetch();
        }
    }
// Wrap (asynctask call) in a own method
public void startFetch() { 
        task = new FetchFacturen();
        task.execute();
    }

private class FetchFacturen extends AsyncTask<Void, Void, Void> {
// Create new AlertDialog
        AlertDialog taskDialog = new AlertDialog.Builder(getActivity())
                .setCancelable(false)
                .setTitle("Mededeling Facturen:")
                .setMessage("Uw sessie is verlopen! U dient zich weer opnieuw in te loggen. ")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Start LoginActivity
                        Intent mainIntent = new Intent(getActivity(), LoginActivity.class);
                        getActivity().startActivity(mainIntent);
                        getActivity().finish();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .create();

        @Override
        protected void onPreExecute() {
            if (Helper.minutes <= 0) {
                task.cancel(true);
            } else {
                showProgress(true);
            }
        }

        @Override
        protected Void doInBackground(Void... result) {
            CharSequence cs1 = "€";
            if (isCancelled()) {
                util.disconnect();
                return null;
            }
                try {
                    // The heavy stuff
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return null;
        }

        @Override
        protected void onCancelled() { //  Correctly called
            if(isCancelled()){
                Log.e("CANCELLED", "TAB3");
                this.taskDialog.show(); 
            }
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Void result) { // Skipped
            if(isCancelled()){
                this.taskDialog.show();
            } else {
                setupInvoiceAdapter();
                showProgress(false);
            }
        }
    }

编辑2:解决了!似乎AsyncTask调用没有正确确定,在代码工作之下,现在 onCancelled方法 被称为并且onPostExecute被拒绝了。 Anudeep Bulla 的荣誉让我指出了正确的方向。

public class Tb3_Abonnement extends Fragment {

private FetchAbbo task;
...
@Override // If Fragment is visible to user, start asynctask
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
                // execute AsyncTask
                task = new FetchAbbo();
                task.execute();
        }

public class FetchAbbo extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            if (Helper.minutes <= 0) {
                task.cancel(true); // Cancel AsyncTask
                new AlertDialog.Builder(getActivity()) // Create new AlertDialog
                        .setCancelable(false)
                        .setTitle("Mededeling:")
                        .setMessage("Uw sessie is verlopen! U dient zich weer opnieuw in te loggen. ")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Start LoginActivity
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .show();
            }
        }

        @Override
        protected Void doInBackground(Void... result) {
                if (!this.isCancelled()) { // Executed 
                    Log.e("FetchAbbo: ", "Cancelled!"); // Printed
                    util.disconnect();
                    return null;
                }
                try {
                    Log.e("FetchAbbo: ", "still running!"); 
                    // Do the heavy stuff
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            return null;
        }

        @Override
        protected void onCancelled() {
            Log.e("CANCELLED", "TAB3"); // Not printed, onCancelled() not called?
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Void result) {
            setupTxtViews();
            mScrollView.setVisibility(View.VISIBLE); // Set ScrollView visible

        }
    }

以下是重要的代码部分:

db.serverStatus()

1 个答案:

答案 0 :(得分:0)

我可能错了,但我似乎并不理解每次在onPreExecute中显示对话框的逻辑。为什么不尝试这个?

public class FetchAbbo extends AsyncTask<Void, Void, Void> {
    AlertDialog taskDialog = new AlertDialog.Builder(getActivity()) // Create new AlertDialog
                                            .setCancelable(false)
                                            .setTitle("Mededeling:")
                                            .setMessage("Uw sessie is verlopen! U dient zich weer opnieuw in te loggen. ")
                                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                                  public void onClick(DialogInterface dialog, int which) {
                                                       // Start LoginActivity
                                                  }
                                            })
                                           .setIcon(android.R.drawable.ic_dialog_info)
                                           .create();
    @Override
    protected void onPreExecute() {
        if (Helper.minutes <= 0) {
            task.cancel(true); // Cancel AsyncTask

        }
    }

    @Override
    protected Void doInBackground(Void... result) {
            if (!this.isCancelled()) { // Executed 
                Log.e("FetchAbbo: ", "Cancelled!"); // Printed
                util.disconnect();
                return null;
            }
            try {
                Log.e("FetchAbbo: ", "still running!"); 
                // Do the heavy stuff
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        return null;
    }

    @Override
    protected void onCancelled() {
        Log.e("CANCELLED", "TAB3"); // Not printed, onCancelled() not called?
        if(this.isCancelled()){
            this.taskDialog.show();
        }
        super.onCancelled();
    }

    @Override
    protected void onPostExecute(Void result) {
        if(this.isCancelled()){
            this.taskDialog.show();
        } else {
            setupTxtViews();
            mScrollView.setVisibility(View.VISIBLE); // Set ScrollView visible
        }

    }
}