android - 如何取消android中的异步任务?

标签 android android-asynctask contacts

您好,在我的应用程序中有一个异步任务来读取联系人详细信息(这需要一点时间)。它运行良好,但问题是当我在异步任务完成之前取消它时,获取详细信息我的应用程序崩溃了.所以我认为当我取消异步任务时让应用程序退出。我在网上搜索并找到了一些方法但它没有用,所以我如何在取消异步任务时退出我的应用程序? 我的Asyn Task代码(普通代码)

public class FetchingContact extends AsyncTask<String, Void, Void> {
    private final ProgressDialog dialog = new ProgressDialog(
            MobiMailActivity.this);

    // can use UI thread here
    protected void onPreExecute() {
        this.dialog.setMessage("Fetching Contact...");
        this.dialog.show();
    }

    // automatically done on worker thread (separate from UI thread)
    protected Void doInBackground(final String... args) {
        readContact();
        if (isCancelled ()) {

            finish();
        }

        return null;
    }

    // can use UI thread here
    protected void onPostExecute(final Void unused) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
            CharSequence test=sam;
            //  search_sort.setText(test);
                check(test);


        }
        // reset the output view by retrieving the new data
        // (note, this is a naive example, in the real world it might make
        // sense
        // to have a cache of the data and just append to what is already
        // there, or such
        // in order to cut down on expensive database operations)
        // new SelectDataTask().execute();
    }

}

最佳答案

AsyncTask 可以随时通过调用 cancel(boolean) 取消。调用此方法将导致对 isCancelled() 的后续调用返回 true。调用此方法后,将在 doInBackground(Object[]) 返回后调用 onCancelled(Object),而不是 onPostExecute(Object)为确保尽快取消任务,您应该始终定期检查 doInBackground(Object[]) 中 isCancelled() 的返回值,如果可能(例如在循环内。)

这是从字面上引用的 AsyncTask .但是由于您已将整个代码放在名为 readContact() 的方法中,因此您不能这样做。

你可以这样做:

protected void onPostExecute(final Void unused) {
    if (this.dialog.isShowing()) {
        this.dialog.dismiss();
        (if !isCancelled()) {
            CharSequence test=sam;
        //  search_sort.setText(test);
            check(test);
        }
    }
}

因此,您在 AsyncTask 结束时检查是否应该做某事。这不是这样做的方法,所以我建议您采用 readContact() 方法,并将其完全放在 AsyncTask 中,或者如果它是 AsyncTask 中的方法,请调用 isCancelled( ) 在那里签到。

关于android - 如何取消android中的异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12036199/

相关文章:

android - 饼图未显示在 fragment 中(Android)

android - AsyncTask 在 ViewPager 的每个页面上运行

javascript - 单击联系表单字段时图像发生变化

android - ArrayList & contains() - 不区分大小写

java - 找不到属性 setter 方法 setAlpha

android - layout_alignParentRight 不适用于线性布局内的相对布局

android - 将数据从一个 Activity 发送到另一个 startactivityforresult

android - ArrayOutOfBounds 将 addHeaderView() 与 EndlessAdapter 一起使用时

android - 如何从获取 NPE 的 Android Activity 调用另一个 Activity AsyncTask 类

Android 如何获取联系人照片的图像路径?