在AsyncTask中获取上下文

我正在尝试获取名为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 Solutions collect form web for “在AsyncTask中获取上下文”

你需要做以下的事情。

  • 当你想要使用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(..); 

由于只有一个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(); } } 

然后你可以访问ActivityContext成员variables

持有主机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 } } 

你可以写getApplicationContex() 。 或者定义全局variables。

 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(); }