0

我正在创建一个 Android 应用程序,并且我对线程一般来说是相当新的我有两种不同的方法用于调用两个不同的 Web 服务,如下所示,那么如何更改这些方法以使用 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;
}
4

1 回答 1

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();
于 2013-05-16T01:45:05.330 回答