2015-07-21 32 views
-1

我想通過它叫成的AsyncTask的的AsyncTask父活動..傳遞一個父活動對象轉換成的AsyncTask

下面是我的代碼的一部分,我想使用doinbackground參數,而不是字符串的活動對象,但我不能因爲我不能從頭做到這一點..請解釋如何做到這一點..

public class Backgroundtask extends AsyncTask<String, Void, String> { 
     AlertDialog alertDialog; 
     AlertDialog alertDialog2; 
     Context ctx; 
     Userlocalstore userlocalstore; 
     String res_name , res_username , res_dob , res_email , res_id , res_pass; 
     Backgroundtask(Context ctx) 
     { 
     this.ctx =ctx; 
     } 

     @Override 
     protected void onPreExecute() { 
     alertDialog = new AlertDialog.Builder(ctx).create(); 
     alertDialog.setTitle("Login Information...."); 
     alertDialog2 = new AlertDialog.Builder(ctx).create(); 

     alertDialog2.setTitle("Apologies"); 
     } 

     @Override 
     protected String doInBackground(String... params) { 
     String reg_url = "http://8miles.freeiz.com/Register.php"; 
     String login_url = "http://8miles.freeiz.com/getuserinfo.php"; 
     String method = params[0]; 
     if (method.equals("Register")) { 
      String name = params[1]; 
      String user_name = params[2]; 
      String user_pass = params[3]; 
      String email = params[4]; 
      String dob = params[5]; 
+2

傳遞的活動進入一個AsyncTask可能有點危險 - 如果AsyncTask永遠不會結束,那麼這個Activity將被泄漏。無論哪種方式,即使在活動完成之後,任務仍會繼續佔用內存,直到任務結束。這包括輪換案件。在這裏小心點。 –

+0

由於Gabe Sechan提到的原因,你可能不應該那樣做,但是你可以簡單地用Activity替換你的Context ctx,因爲Activity也是一個Context。 – BladeCoder

回答

0

BackgroundtaskActivity中的內部類?如果是這樣,你不需要通過Context參數。相反,您可以使用*ActivityName*.this

除此之外,你的方法看起來不錯。你可能想讓你的構造函數public

+0

隱式引用是很難引用的,所以這會是一個潛在的泄漏。 –

0

http://developer.android.com/reference/android/os/AsyncTask.html站點:「參數,執行時發送給任務的參數的類型」。所以,當你擴展你的Backgroundtask的的AsyncTask類,你可以說:

public class Backgroundtask extends AsyncTask<GenericTypeOfYourChoice, Void, String> 

,並通過你的對象作爲.execute()方法的第一個參數,如:

new Backgroundtask().execute(instanceOfGenericTypeOfYourChoice); 
相關問題