调用Http Get函数时,Android应用程序会冻结

时间:2013-08-30 06:26:29

标签: android android-asynctask

我的应用从网站读取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();
                }
             }
        });
    }

但是当调用此方法时,应用程序会冻结一段时间。怎样成为?如何在背景上这样做?

3 个答案:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您的代码表示您使用Strict Mode政策在主界面中运行与网络相关的操作。强烈建议您不要这样做。请AsynTask执行此任务。

相关问题