如何在不泄漏上下文的情况下在AsyncTask中显示AlertDialog?

时间:2019-05-25 17:36:30

标签: android android-asynctask

我有下面的代码可以正常工作,以通过id在Room数据库中查找和读取记录。 Android Studio需要添加一个try / catch块,我已在下面添加了它。

两个问题: 如果没有异常,是否可以在onPostExecute()中将if {}部分留空?

如何在此处显示AlertDialog而不泄漏连接且不通过WeakReference使用hack?

// AsyncTask for reading an existing CardView from the database.
private static class ReadAsyncTask extends AsyncTask<Integer, Void, Quickcard> {

    private QuickcardDao asyncTaskDao;
    Exception e;

    ReadAsyncTask(QuickcardDao dao) {
        asyncTaskDao = dao;
    }

    @Override
    public Quickcard doInBackground(final Integer... params) {

        Quickcard result;
        try {
            result = asyncTaskDao.readCardForUpdate(params[0]);

        } catch (Exception e) {
            this.e = e;
            result = null;
        }
        return result;
    }

    @Override
    protected void onPostExecute(Quickcard quickcard) {

        if (e == null) {
            // *** Okay to leave this blank?  If not, what should go here?
        }
        else {
            // *** How do I show an AlertDialog here with leaking context?
        }
    }
}    

2 个答案:

答案 0 :(得分:0)

使用在后台运行的线程时不能使用视图对象。U必须在UI线程中实现对话框。在实现异步类时,在该方法中应显示警告对话框。希望对您有所帮助。

答案 1 :(得分:0)

这是我要采取的措施,以防止发生泄漏。

  private static class showDialog extends AsyncTask<String, String, String> {

    private WeakReference<MainActivity> mainActivityWeakReference;

    showDialog(MainActivity mainActivity){
        this.mainActivityWeakReference = new WeakReference<>(mainActivity);

    }
    @Override
    protected String doInBackground(String... params) {
        //do your long long time consuming tasks here.
        return "Done";
    }


    @Override
    protected void onPostExecute(String result) {
        // execution of result of Long time consuming operation
        //Just building an alert dialog to show.
        if (mainActivityWeakReference.get() != null){
            final MainActivity activity = mainActivityWeakReference.get();
            new AlertDialog.Builder(activity).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Toast.makeText(activity, "Yes was clicked", Toast.LENGTH_SHORT).show();
                }
            }).show();
        }
    }


    @Override
    protected void onPreExecute() {
    }


    @Override
    protected void onProgressUpdate(String... text) {

    }
}