简体   繁体   English

内部AsyncTask类内部还是外部的AlertDialog.Builder声明?

[英]AlertDialog.Builder declaration inside or outside inner AsyncTask class?

Consider this AsyncTask inside activity MyActivity : 考虑活动MyActivity AsyncTask

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

    private ProgressDialog progressDialog;
    private AlertDialog.Builder alertDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(MyActivity.this, "MyApp", "Working...");
    }

    @Override
    protected Void doInBackground(Void... params) {
        // elaborate...
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        progressDialog.dismiss();

        alertDialog = new AlertDialog.Builder(MyActivity);
        alertDialog.setMessage("Done !");
        alertDialog.show();
    }
}

What happen if I declare 如果我声明会怎样?

private ProgressDialog progressDialog;
private AlertDialog.Builder alertDialog;

outside the AsyncTask , in the activity scope? AsyncTask之外,在活动范围内?

Is it really the same (for memory leaks and other inner Java behaviours)? 是否真的一样(对于内存泄漏和其他内部Java行为)? Is one better than the other? 这个比那个好吗?

Not quite sure what you mean by 'the same'. 不太确定“相同”是什么意思。 But if you are talking about the scope of both progressDialog and alertDialog then the answer would definitely be no. 但是,如果您同时讨论progressDialog和alertDialog的范围,那么答案肯定是“否”。 A variable belongs to the class that declares it. 变量属于声明它的类。

Basically what both progressDialog and alertDialog actually need is just a reference to a Context instance(In your case is 'MyActivity') in order for it to be instantiated and displayed, hence it doesn't matter where they are created as long as that Context object is available. 基本上,progressDialog和alertDialog实际需要的只是对Context实例的引用(在您的情况下为'MyActivity'),以便实例化和显示该实例,因此,只要在该Context中创建它们就无关紧要对象可用。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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