2013-05-16 24 views
0

我正在創建一個Android應用程序,並且對於線程來說我還是比較新的一般我有兩種不同的方法用於調用兩個不同的Web服務,如下所示,所以如何更改這些以使用AsyncTask在後臺線程上運行?如何爲此添加AsyncTask?

我的代碼:

public List<String> getEvacRouteNames(){ 
    if (android.os.Build.VERSION.SDK_INT > 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    } 


    BufferedReader in = null; 
    String page; 

    try { 


     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(); 
     request.setURI(URI) 
     //Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field 
     List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(0); 
     request.setEntity(new UrlEncodedFormEntity(nameValPairs)); 

     HttpResponse response = client.execute(request); 
     in = new BufferedReader 
     (new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
      sb.append(line + NL); 

     } 
     in.close(); 
     page = sb.toString(); 


     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     Document doc = db.parse(new InputSource(new StringReader(page))); 
     // normalize the document 
     doc.getDocumentElement().normalize(); 
     // get the root node 
     NodeList nodeList = doc.getElementsByTagName("string"); 
     // the node has three child nodes 
     for (int n = 0; n < nodeList.getLength(); n++) { 
      Node node=nodeList.item(n); 
      String upperNode = node.getNodeName(); 
      Node temp=node.getChildNodes().item(n); 
      if (upperNode.equals("string")){ 
       String routeName = node.getTextContent(); 
       routeNamesList.add(node.getTextContent()); 
      } 
     } 

     //System.out.println(page); 
     } catch (Exception E) { 
      E.printStackTrace(); 
     } 
    finally { 
     if (in != null) { 
      try { 
       in.close(); 
       } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return routeNamesList; 
} 

public EvacRoute getEvacuationRoute(String routeName, LatLng currentLocation, String lat, String lon) throws URISyntaxException, ClientProtocolException, IOException, ParserConfigurationException, SAXException{ 
    evacRouteList = new ArrayList<EvacRoute>(); 
    if (android.os.Build.VERSION.SDK_INT > 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    } 
    EvacRoute evacRoute = new EvacRoute(); 
    evacRoute.setDestinationName(routeName); 
    BufferedReader in = null; 
    String page; 
    latslngsList = new ArrayList<LatLng>(); 
    try { 

     latslngsList.add(currentLocation); 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(); 
     request.setURI(URI) 
     //Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field 
     List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(2); 
     nameValPairs.add(new BasicNameValuePair("Route_Name", routeName)); 
     nameValPairs.add(new BasicNameValuePair("In_Lat", lat)); 
     nameValPairs.add(new BasicNameValuePair("In_Lon", lon)); 
     request.setEntity(new UrlEncodedFormEntity(nameValPairs)); 

     HttpResponse response = client.execute(request); 
     in = new BufferedReader 
     (new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
      sb.append(line + NL); 

     } 
     in.close(); 
     page = sb.toString(); 


     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     Document doc = db.parse(new InputSource(new StringReader(page))); 
     // normalize the document 
     doc.getDocumentElement().normalize(); 
     // get the root node 
     NodeList nodeList = doc.getElementsByTagName("simple_ll_waypoint"); 
     double latitude = 0; 
     double longitude= 0; 
     // the node has three child nodes 
     for (int n = 0; n < nodeList.getLength(); n++) { 
      String latString = ""; 
      String longString = ""; 

      Node node=nodeList.item(n); 
      String upperNode = node.getNodeName(); 
      StringBuilder addressStrBlder = new StringBuilder(); 
      for (int i = 0; i < node.getChildNodes().getLength(); i++) { 
       Node temp=node.getChildNodes().item(i); 
       String nodeName = temp.getNodeName(); 
       String nodevalue = temp.getNodeValue(); 
       if(temp.getNodeName().equalsIgnoreCase("Lat")){ 
        latString = temp.getTextContent(); 
        latitude = Double.parseDouble(latString); 

       } else if(temp.getNodeName().equalsIgnoreCase("Lon")){ 
        longString = temp.getTextContent(); 
        longitude = Double.parseDouble(longString); 
        LatLng latlng = new LatLng(latitude, longitude); 
        latslngsList.add(latlng); 
       } 

      } 
      //Log.e("Fuel Stop", fuelStop.toString()); 
     } 

     //System.out.println(page); 
     } catch (Exception E) { 
      E.printStackTrace(); 
     } 
    finally { 
     if (in != null) { 
      try { 
       in.close(); 
       } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    evacRoute.setLatLngList(latslngsList); 
    evacRouteList.add(evacRoute); 
    return evacRoute; 
} 

回答

2

您可以從AsyncTask擴展您的類和這樣做:

public class AsyncCustomTask extends AsyncTask<Void, Void, List<String>> { 

     @Override 
     protected List<String> doInBackground(Void... params) { 
       return getEvacRouteNames(); 
      } 

      @Override 
     protected void onPostExecute(List<String> result) { 
      // Function finished and value has returned. 
     } 

    } 

,並呼籲它:

new AsyncCustomTask().execute(); 

更新了第二個問題

對於有參數的方法,你可以使用你的類一樣的構造函數:

public class AsyncSecondCustomTask extends AsyncTask<Void, Void, EvacRoute> { 

     private final String routeName; 
     private final LatLng currentLocation; 
     private final String lat; 
     private final String lon; 

     public AsyncSecondCustomTask(String routeName, LatLng currentLocation, String lat, String lon) { 
      this.routeName = routeName; 
      this.currentLocation = currentLocation; 
      this.lat = lat; 
      this.lon = lon; 
     } 

     @Override 
     protected EvacRoute doInBackground(Void... params) { 
      return getEvacuationRoute(routeName, currentLocation, lat, lon); 
     } 

     @Override 
     protected void onPostExecute(EvacRoute result) { 
      // Function finished and value has returned. 
     } 

    } 

你可以這樣調用它:

new AsyncSecondCustomTask("", null, "", "").execute(); 
+0

但我在同一個類中的兩個不同的Web服務調用我怎麼做? – yams

+0

而且我該如何稱呼它? – yams

+0

您可以爲任一個創建不同的類或對象實例。 – JustWork