【问题标题】:What is the best way of getting / using Context inside AsyncTask?在 AsyncTask 中获取/使用 Context 的最佳方式是什么?
【发布时间】:2013-08-20 09:48:58
【问题描述】:

我通过扩展AsyncTask 类定义了一个单独的线程。在这个类中,我在 AsyncTask 的 onPostExecuteonCancelled 方法中执行了一些 Toast 和 Dialogs。祝酒词需要应用程序的上下文,因此我需要做的就是:

Toast.makeText(getApplicationContext(),"Some String",1);

对话框是使用AlertDialog.Builder 创建的,这也需要在其构造函数中包含上下文。我认为这个上下文应该是活动的上下文是否正确?即

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  

其中getActivity 可以是返回当前活动的用户定义类。如果是这样,处理这种情况的最佳方法是什么?创建类似getActivity 的类或将当前活动的上下文传递给 AsyncTask 的构造函数?

我想我想了解Context 的使用 - 我注意到内存泄漏可能是一个问题(还不太了解)以及如何使用getApplicationContext() 是可能的最佳方法。

【问题讨论】:

    标签: android constructor android-asynctask inner-classes android-context


    【解决方案1】:

    只需将 AsyncTask 创建为 Activity 的内部类,或将 Context 传递给 AsyncTask 的构造函数。

    内部类: MyActivity.java

    public class MyActivity extends Activity {
    
        // your other methods of the activity here...
    
    
        private class MyTask extends AsyncTask<Void, Void, Void> {
    
             protected Void doInBackground(Void... param) {
    
                 publishProgress(...);  // this will call onProgressUpdate();
             }
    
             protected Void onProgressUpdate(Void... prog) {
    
                 Toast.makeText(getActivity(), "text", 1000).show(); 
             }
        }
    }
    

    构造函数: MyTask.java

    public class MyTask extends AsyncTask<Void, Void, Void> {
    
         Context c;
    
         public MyTask(Context c) {
              this.c = c;
         }
    
         protected Void doInBackground(Void... param) {
    
              publishProgress(...);  // this will call onProgressUpdate();
         }
    
         protected Void onProgressUpdate(Void... prog) {
              Toast.makeText(c, "text", 1000).show();
         }
    }
    

    此外,请不要忘记在您的 Dialog 上调用 .show()

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.show();
    

    【讨论】:

    • 谢谢菲尔。我的 AsyncTask 当前是我的活动的内部类(如上所示)。但是,虽然这适用于 MyTask 的 UI 方法中的 Toast.makeText(getApplicationContext(), ...,但 AlertDialog.Builder(getApplicationContext()) 不起作用。我想这是因为它没有得到正确的上下文?因此,是否不需要将活动的上下文传递给MyTask 的构造函数?还是我错过了什么?
    • 你能发布你在哪里制作对话的完整代码吗?也不要忘记在 Dialog 上调用 .show()。
    • 好的,好的! ToastAlertDialog 在将上下文传递给MyTask 的构造函数时都可以工作,如上所示,即使用MyTask(this) 从主活动中的onClick 事件实例化MyTask。对,所以我只需要澄清一下:MyTask(this) 将活动的上下文传递给MyTaskToastAlertDialog 都可以使用它。然而,虽然Toast 可以使用getApplicationContext() 使用应用程序上下文,但AlertDialog 不能,即它需要活动的上下文 - 认为那是我出错的地方。
    • 标记为正确!显然需要更多积分来评价它:(。干杯菲尔
    • 这个例子怎么不是上下文的内存泄漏?如果活动被破坏了,内部的 asyncTask 仍然持有对上下文的强引用,所以它可以被垃圾收集,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多