java - 如何向其中添加 AsyncTask?

标签 java android eclipse web-services android-asynctask

我正在创建一个 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;
}

最佳答案

您可以从 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();

关于java - 如何向其中添加 AsyncTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577700/

相关文章:

php - 在 eclipse pdt 中同步时 - 在比较 php 文件的版本时得到一个空白的灰色窗口

java - 向 Jframe 添加控制台

java - eclipse:用 if 包围 block

java - Eclipse SWT ScrolledComposite 拒绝滚动

android - 在 Android Studio 中安装终极版 IntelliJ 插件

Android Studio - Android Emulator 以不同方式呈现布局。模拟器运行程序时高度似乎变小了

android - 在 android 应用程序中进行服务器通信的后台服务的最佳方式

java - Sonarqube 未正确显示 Java 项目的测试覆盖率

java - 使用 Props 初始化 actor

java - 由于某种原因,我的 java 类不会继承 public void。有人可以帮助我吗?