1

我在 android 中运行 Async(doInBackground) 任务。

我需要为任务填充进度条。所以我在onPreExecute中显示了一个progressDialog,

ProgressDialog.show 的签名是 Show(Context,Title,message)

但是这里的上下文是什么?

 @Override
protected void onPreExecute() 
{
    progress = ProgressDialog.show(???, "Loading", "Please Wait");
}
4

6 回答 6

2

为您的 AsyncTask 创建一个将上下文作为参数的构造函数。

public class async extends AsyncTask<String, Integer, String>{

    private Context context;

    public async(Context context) {
      this.context = context;
     }


    @Override
    protected void onPreExecute() {
     // Manipulate progress bar      
    }

然后使用它来执行它

async mTask = new async(context).execute(params);
于 2013-05-15T13:38:58.687 回答
1

上下文只能是 Activity 、Service 或 Brodcast 不能属于任何其他类,如 Asyncktask。因此,将该 Activity 的 Context 放在您使用该 AsyncTask 类的位置。

于 2013-05-15T13:40:05.913 回答
1

您可以在 AsyncTask 构造函数中传递活动上下文来创建 ProgressDialog :

MyAsyncTask 构造函数:

public MyAsyncTask(Context context){
     progressDialog = new ProgressDialog(context, "Loading", "Please wait...");
}

onPreExecute 方法:

@Override
protected void onPreExecute() 
{
    progressDialog.show();
}

或存储上下文并在 onPreExecute 方法中创建对话框(但我更喜欢使用第一种方式):

public class MyAsyncTask extends AsyncTask{
     private Context mContext;

     public MyAsyncTask(Context context){
          this.mContext = context; 
     }

     @Override
     protected void onPreExecute() 
     {
          progress = ProgressDialog.show(this.mContext, "Loading", "Please Wait");
     }
}

在声明 MyAsyncTask 的活动中,您传递活动:

MyAsyncTask asyncTask = new AsyncTask(this);
asynchTask.execute();
于 2013-05-15T13:53:28.583 回答
1
Add this function in your class

   private Context getDialogContext() {
    Context context;
    if (getParent() != null)
        context = getParent();
    else
        context = this;
    return context;
}

In your asynctask use it as follows

  @Override
  protected void onPreExecute() 
  {
    progress = ProgressDialog.show(getDialogContext(), "Loading", "Please Wait");
    }
于 2013-05-15T18:47:55.417 回答
0

如果您只想this用作上下文,那么您的 Asynctask 应该被编写为扩展 Activity 类的类的内部类。然后你的上下文是扩展 Activity 的类的名称。像这样传递上下文仍然是更好的做法:

ClassExtendingActivity.this
于 2013-05-15T13:38:48.977 回答
-1

您可以传递当前活动视图参考,例如MainActivity.this

于 2013-05-15T13:37:12.033 回答