android - 在 AsyncTask 中获取上下文

标签 android android-asynctask toast android-context

我正在尝试在名为 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(); 
}

但它对我不起作用,它说:“范围内没有 Opciones 类型的封闭实例”

最佳答案

你需要做以下事情。

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

关于android - 在 AsyncTask 中获取上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16920942/

相关文章:

android - 使用线性加速度和时间传递来获得行进距离 - android

android - 如何在 onPause Activity 中解散之前等待 ProgressDialog

Android java.util.concurrent.RejectedExecutionException : Task android. os.AsyncTask被java.util.concurrent拒绝

android - 我可以确定对 Activity 的引用是否有效吗?

notifications - Windows 8 Metro 应用程序 - toast 通知

c# - 在锁定屏幕上显示 UWP 控件

Android chrome 数据保护程序 - 它是如何工作的

android - 如何在 Intellij IDEA 中运行 Proguard

android - OsmBonuspack - GeocoderNominatim::getFromLocationName - 来自服务器的无效响应:HTTP/1.1 403 Forbidden

android - 区别以及何时使用 getApplication()、getApplicationContext()、getBaseContext() 和 someClass.this