2013-04-05 85 views
0

對於此代碼段(我已排除doInBackground(), postExecute()等) 如何在從CheckServer活動調用異步任務時傳遞Activity參數?從活動中調用AsyncTask

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

創建構造函數HttpTicket(Activity)。 HttpTicket ticket = new HttpTicket(Activity.this); ticket.execute(); – Amit 2013-04-05 08:36:22

回答

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 
    } 


    } 
0

可以sipmly做

HttpTicket mHttpTicket = new HttpTicket(this); 
mHttpTicket.execute(); 

你也可以刪除構造函數,只是傳遞給OnPr e執行爲參數。然後你給它在execute(this);