2013-05-16 2 views
0

Я создаю приложение для Android, и я довольно новичок в потоковом режиме. У меня есть два разных метода, которые я использую для вызова двух разных веб-сервисов, как показано ниже, поэтому как это изменить, чтобы использовать 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

Но у меня есть два разных вызовов веб-сервиса в одном классе как это сделать? – yams

+0

А также как мне это назвать? – yams

+0

Вы можете создать разные экземпляры классов или объектов для одного. – JustWork