86

我试图在名为 Opciones 的类的 AsyncTask 中获取上下文(该类是唯一调用该任务的类),但我不知道该怎么做,我看到了一些这样的代码:

      protected void onPostExecute(Long result) {

    Toast.makeText(Opciones.this,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show(); 
}

但它对我不起作用它说:"No enclosing instance of the type Opciones in scope"

4

4 回答 4

181

你需要做以下事情。

  • 当你想使用AsyncTask时,在其他类中扩展它说MyCustomTask
  • 在新类的构造函数中,传递Context

例子

public class MyCustomTask extends AsyncTask<Void, Void, Long> {

    private Context mContext;

    public MyCustomTask (Context context){
         mContext = context;
    }

    //other methods like onPreExecute etc.
    protected void onPostExecute(Long result) {
         Toast.makeText(mContext,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show(); 
    }
}

并通过以下方式实例化类。

MyCustomTask task = new MyCustomTask(context);
task.execute(..);
于 2013-06-04T14:57:13.833 回答
62

持有对宿主 Activity 的弱引用将防止内存泄漏。

static class MyTask extends AsyncTask<Void, Void, Void> {
    // Weak references will still allow the Activity to be garbage-collected
    private final WeakReference<Activity> weakActivity;

    MyTask(Activity myActivity) {
      this.weakActivity = new WeakReference<>(myActivity);
    }

    @Override
    public Void doInBackground(Void... params) {
      // do async stuff here
    }

    @Override
    public void onPostExecute(Void result) {
      // Re-acquire a strong reference to the activity, and verify
      // that it still exists and is active.
      Activity activity = weakActivity.get();
      if (activity == null
          || activity.isFinishing()
          || activity.isDestroyed()) {
        // activity is no longer valid, don't do anything!
        return;
      }

      // The activity is still valid, do main-thread stuff here
    }
  }
于 2017-07-08T03:43:38.820 回答
13

由于只有一个人Activity使用此任务,因此只需使其成为该任务的内部类Activity

public class Opciones extends Activity
{
     public void onCreate()
     {
         ...
     }

    public class MyTask extends AsyncTask<>
    {
        ...

         protected void onPostExecute(Long result) {
        Toast.makeText(Opciones.this,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show(); 
     }
}

然后您可以访问 theActivity及其成员变量Context

于 2013-06-04T14:59:34.843 回答
-7

你可以写getApplicationContex()。或定义全局变量。

Activity activity;

onCreate()功能上

activity = this;

然后,

 protected void onPostExecute(Long result) {

    Toast.makeText(activity,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show(); 
}
于 2013-06-04T14:58:49.190 回答