如何为此添加AsyncTask?

时间:2013-05-16 01:40:07

标签: java android eclipse web-services android-asynctask

我正在创建一个Android应用程序,我对线程一般相当新我有两个不同的方法,我用来调用两个不同的webservices,如下所示,所以我如何更改这些以使用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;
}

1 个答案:

答案 0 :(得分: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();