对于此代码段(我排除了doInBackground(), postExecute()
等)
从CheckServer活动调用异步任务时,我应该如何传递Activity参数?
public class CheckServer extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
HttpTicket ticket= new HttpTicket(); //HOW IS THIS LINE DONE? WHAT PARAM SHOULD BE PASSED?
}
@SuppressWarnings("unused")
private class HttpTicket extends AsyncTask<String, String, String>
{
private Activity activity;
private ProgressDialog dialog;
public HttpTicket(Activity activity) {
this.activity = activity;
}
答案 0 :(得分:0)
在你的活动onCreate()
中 HttpTicket ticket= new HttpTicket(Activity.this);
//passing context to the asynctask constructor
ticket.execute();
//call execute to laod asynctask
将asynctask定义如下
private class HttpTicket extends AsyncTask<String, String, String>
{
private Activity activity;
private ProgressDialog dialog;
public HttpTicket(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
dialog.setTitle("Wait...");
}
protected void onPreExecute()
{
dialog.show();
}
protected String doInBackground(String params)
{
//background opearation
return "string";
}
protected void onPostExecute(String result)
{
dialog.dismiss();
//update ui
}
}
答案 1 :(得分:0)
你可以狡猾地做
HttpTicket mHttpTicket = new HttpTicket(this);
mHttpTicket.execute();
您也可以删除构造函数,然后将其作为参数传递给OnPreExecute。然后你在execute(this);