在 AsyncTask 中获取上下文 [英] getting context in AsyncTask

查看:43
本文介绍了在 AsyncTask 中获取上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get the context in my AsyncTask of the class called Opciones(this class is the only one that call that task) but I don't know how to do it, I saw some code like this:

      protected void onPostExecute(Long result) {

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

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

But it doesn't work for me it says: "No enclosing instance of the type Opciones in scope"

推荐答案

你需要做以下事情.

  • 如果您想使用 AsyncTask,请在其他类中扩展它,例如 MyCustomTask.
  • 在新类的构造函数中,传递Context
  • when you want to use AsyncTask, extend that in other class say MyCustomTask.
  • in constructor of new class, pass 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(); 
    }
}

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

And instantiate class by following.

MyCustomTask task = new MyCustomTask(context);
task.execute(..);

这篇关于在 AsyncTask 中获取上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆