android,ICS中的android.os.networkonmainthreadexception

时间:2012-11-17 20:12:01

标签: android

try {
    URL url = null;
    url = new URL(url_string);
    URLConnection conn = url.openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line="";
    while((line = reader.readLine())!=null){
        Log.d("html",line);
    }

} catch (Exception e) {
    Log.d("Exception Error: ",e.toString());
}

我只是在阅读网站,我收到android.os.networkonmainthreadexception错误

我的代码非常简单..请看一下,请告诉我我需要做什么..

谢谢,

2 个答案:

答案 0 :(得分:3)

您需要将网络访问权限移至后台线程,例如通过AsyncTask。您目前正在尝试在主应用程序线程上执行网络I / O,这不是一个好主意。

答案 1 :(得分:0)

使用此类运行后台任务..

    public class getConnection extends AsyncTask<String, Void, Void> 
    {


           @Override
            protected void onPreExecute() 
           {
               super.onPreExecute();
               Utils.clearDialogs();
               Utils.showActivityViewer(Mainctivity.this);
           }

           @Override
           protected Void doInBackground(String... arg0)
           {

            try 
            {

               URL url = null;
url = new URL(url_string);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line="";
while((line = reader.readLine())!=null){
    Log.d("html",line);
            } 
            catch (Exception e) 
            {
             e.printStackTrace();
            }

            return null;
           }

           @Override
           protected void onPostExecute(Void result)
           {
               super.onPostExecute(result);
               Utils.hideActivityViewer();

            }
            catch (Exception e)
            {
             Log.v("log", e.toString());
            }
           }

          }