-1

我的应用程序从站点读取 xml。我有这段代码来获取 xml 内容。

public String getPage(String url){
        try {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build();
            StrictMode.setThreadPolicy(policy);
            BufferedReader in = null;
            String data = null;
            try
            {
                HttpClient client = new DefaultHttpClient();
                URI website = new URI(url);
                HttpGet request = new HttpGet();
                request.setURI(website);
                HttpResponse response = client.execute(request);
                response.getStatusLine().getStatusCode();

                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String l = "";
                String nl = System.getProperty("line.separator");
                while ((l = in.readLine()) !=null){
                    sb.append(l + nl);
                }
                in.close();
                data = sb.toString();

                return data;        
            } finally{
                if (in != null){
                    try{
                        in.close();
                        return data;
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            //return e.toString();
            return "No Internet Connection";
            //e.printStackTrace();
        }
    }

我从这里调用它

public void axtarHandler_run(){
        runOnUiThread(new Runnable() {
             public void run() {
                TextView axtarish_key = (TextView) findViewById(R.id.axtarish_key);
                String netice;
                try {
                    netice = getPage("http://somedomain.com/search.php?query="+URLEncoder.encode((String) axtarish_key.getText().toString(),"UTF-8"));
                    ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

                    final XMLParser parser = new XMLParser();
                    String xml = netice; // getting XML from URL
                    Document doc = parser.getDomElement(xml); // getting DOM element

                    final NodeList nl = doc.getElementsByTagName(KEY_SONG);
                    // looping through all song nodes <song>
                    for (int i = 0; i < nl.getLength(); i++) {
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        Element e = (Element) nl.item(i);
                        // adding each child node to HashMap key => value
                        map.put(KEY_ID, parser.getValue(e, KEY_ID));
                        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));

                        // adding HashList to ArrayList
                        songsList.add(map);
                    }

                    list=(ListView)findViewById(R.id.list);

                    // Getting adapter by passing xml data ArrayList
                    adapter=new LazyAdapter(parentActivity, songsList, R.layout.list_row);
                    list.setAdapter(adapter);

                    // Click event for single list row
                    list.setOnItemClickListener(new OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
                            Element e = (Element) nl.item(position);
                            String music_id = parser.getValue(e, KEY_ID);
                            String music_name = parser.getValue(e, KEY_TITLE);
                            parentActivity.play_music_forsearch(Integer.toString(position), music_id, music_name);
                        }
                    });

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             }
        });
    }

但是当调用此方法时,应用程序会冻结一段时间。怎样成为?如何在后台执行此操作?

4

3 回答 3

1
class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

然后,您可以通过以下方式提出请求:

 new RequestTask().execute("http://stackoverflow.com");
于 2013-08-30T06:30:24.933 回答
0

您正在 UI 线程上运行它。不要那样做。请改用AsyncTask

于 2013-08-30T06:28:45.380 回答
0

您的代码表明您正在使用策略在主 UI 中运行与网络相关的操作。Strict Mode强烈建议不要这样做。使用AsynTask来执行此任务。

于 2013-08-30T06:28:59.140 回答