2013-12-10 82 views
0

我想從異步任務中獲取結果。如果我使用task.execute.get,我的UI將被凍結。我希望我的異步任務將是獨立的類,所以我不想將結果處理代碼放在onPostExecute中。我發現約回撥從這裏異步任務數據的一些信息:http://blog.evoxmusic.fr/content/how-implement-callback-asynctask
這裏:android asynctask sending callbacks to ui
但問題是: 1 - 我不知道什麼時候才能處理結果? 2-爲什麼要使用界面? 3-使用接口的簡單方法是將結果放入公共字段中的onPostExecute異步任務中有什麼區別?從異步任務中獲取結果

這是我的異步類:

public class AsyncCallWs extends AsyncTask<String, Void, String> { 

    private ProgressDialog dialog; 
    public String methodName=""; 
    private WebService ws; 
    private ArrayList<ServiceParam> paramsList; 
    private boolean hasParams; 

    public AsyncCallWs(Activity activity,String methodName) { 
     xLog.position(); 
     try { 
      this.dialog = new ProgressDialog(activity); 
      this.methodName = methodName; 
      hasParams = false; 
     } catch (Exception e) { 
      xLog.error(e.getMessage()); 
     } 
    } 

    public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) { 
     xLog.position(); 
     try { 
      this.dialog = new ProgressDialog(activity); 
      this.methodName = methodName; 
      this.paramsList = params; 
      hasParams = true; 
     } catch (Exception e) { 
      xLog.error(e.getMessage()); 
     } 
    } 


    @Override 
    protected void onPreExecute() { 
     this.dialog.setMessage(PersianReshape.reshape("Loading...")); 
     this.dialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     xLog.position(); 
     String result = "No async task result!"; 
     try { 
      ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL); 
      if (!hasParams){ 
       result = ws.CallMethod(methodName); 
      } 
      else{ 
       xLog.info("THIS METHOD IS: "+ methodName); 
       result = ws.CallMethod(methodName,paramsList); 
       xLog.info("THIS RESULT IS: "+ result); 
      } 
     } catch (Exception e) { 
      xLog.error(e.getMessage()); 
     } 
     return result; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     xLog.position(); 

     if (this.dialog.isShowing()) { 
      this.dialog.dismiss(); 
     } 
     xLog.info("Output of current AsyncTask is:"+ result); 
    } 
} 
+0

使用inteface和回調方法,您將發送您收到的數據 – Eddy

回答

1

1-我不知道何時處理結果?

結果將在onPostExecute中處理,反過來將在任何實現此接口的類中調用您的接口方法。所以實際的用戶界面的東西都將發生在你的ActivityFragment或任何正在實現接口回調。你可以傳遞你想要的任何數據。

2-why interface interface?

接口是從你的AsyncTask和任何類解耦邏輯的好方法(我假設一個ActivityFragment),而實現它。這也意味着任何實現這個接口的類都可以處理這個AsyncTask的結果,它很容易重用。

3-使用接口與簡單地將結果放入公共字段中的異步任務onPostExecute有什麼區別?

你仍然不會得到一個回調 - 如何將你的ActivityFragment知道是填充這個領域的時候,隨時可以詢問?

0

對於基礎知識的關注..

步驟(1)啓動異步任務

new BussinessOwnerHttpAsyncTask().execute(); 

步驟(2)創建的AsyncTask類像這樣

class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 
// Here U perform all your basics task like start showing progress bar as mentioned below. //@Android Hacker 
// On OnPostExecute method U stop your progress dialog after all data has been fetched 
// @Android Hacker 
      pDialog = new ProgressDialog(getParent()); 
      pDialog.setMessage("Please wait ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     @Override 
     protected String doInBackground(String... params) { 


// Here U fetch all data from server @Android Hacker 

      // Maintaining Shared preferences class for further... 

      SharedPreferences sp = getSharedPreferences("search_data", 0); 
      SharedPreferences.Editor editor = sp.edit(); 
      editor.putString("service_name", service_name); 
      editor.putString("city_name", city_name); 
      editor.putString("loc", city_name + ", " + country_name); 
      editor.putString("country_name", country_name); 
      editor.putString("pMonth", (checkDigit(pMonth + 1))); 
      editor.putString("day", day); 
      editor.putString("year", year); 
      editor.putString("d", year + "-" + checkDigit(pMonth + 1) + "-" + day); 
      editor.commit(); 

      HttpClient httpclient = new DefaultHttpClient(); 
      String loc = ""; 
      String sdate = ""; 

      try{ 

       if(pDisplayDate.getText().toString().equalsIgnoreCase("")){ 
        sdate = year + "-" + checkDigit(pMonth + 1) + "-" + day; 
       }else{ 
        sdate = date; 
       } 
      }catch(Exception e){ 
       e.printStackTrace(); 
      } 

      if(etlocation.getText().toString().length() == 0){ 
       city_name = ""; 
       country_name = "Kuwait"; 
       loc = "" + ", " + "Kuwait"; 
      }else{ 
       loc = city_name + ", " + country_name; 
      } 


      String myUrl = service_name + "~" + city_name + "~" 
        + country_name + "~" + date 
        + "~" + service_recog_id; 

      if(city_name.equalsIgnoreCase("")){ 
       locations = "Kuwait"; 
      }else{ 
       locations = city_name + ", " + country_name; 
      } 

      SharedPreferences m = getSharedPreferences("modify", 0); 
      SharedPreferences.Editor eee = m.edit(); 
      eee.putString("service", service_name); 
      eee.putInt("service_recog_id", service_recog_id); 
      eee.putString("location", loc); 
      eee.putString("date", sdate); 
      eee.putString("locations", locations); 
      eee.commit(); 


      String encodedURL = ""; 
      try { 
       encodedURL = URLEncoder.encode(myUrl, "UTF-8"); 
      } catch (UnsupportedEncodingException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      try { 
       URL url = new URL(encodedURL); 
       Log.d("asca", ""+url); 
      } catch (MalformedURLException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

      Log.i("url", city_name + "~" + country_name); 
      Log.d("location", request_url+encodedURL); 
      HttpGet httpget = new HttpGet(request_url+encodedURL); 

      try { 
       httpresponse = httpclient.execute(httpget); 
       System.out.println("httpresponse" + httpresponse); 
       Log.i("response", "Response" + httpresponse); 
       InputStream is = httpresponse.getEntity().getContent(); 
       InputStreamReader isr = new InputStreamReader(is); 
       BufferedReader br = new BufferedReader(isr); 
       StringBuilder sb = new StringBuilder(); 

       String recievingDataFromServer = null; 
       while ((recievingDataFromServer = br.readLine()) != null) { 
        Log.i("CHECK WHILE", "CHECK WHILE"); 
        sb.append(recievingDataFromServer); 
       } 

       myJsonString = sb.toString(); 
       Log.d("manish", myJsonString); 
       serverSearchData = sb.toString(); 
      } catch (ClientProtocolException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return sb.toString(); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 
      pDialog.dismiss(); 

// @Android Hacker .. Here U perform all your task for UI . Here U get data and set that //data to UI 


     } 

    } 

希望它清除你所有的疑惑..

+0

感謝您的回覆,但它就像我的Async任務類。我的問題呢? –