问题描述
|
我试图编写一些从用户处获取URL的代码,然后单击“提交”按钮后,我将获取该URL并进行调用,并从页面中检索html源代码。但是,我得到以下例外:
W / System.err(14858):android.os.networkonmainthreadException
W / System.err(14858):位于android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
似乎对于android 3.0,我尝试开发的平台不允许我在主要方法上使用网络资源。我了解有些方法可以在后台运行它或使用async方法起作用,但是有人可以对此进行指导吗?我不太确定该怎么做。我是编程新手。
提前致谢。
下面是我当前的代码,在onclick方法上:
String htmlCode = \"\";
try {
URL url = new URL(\"http://www.google.com\");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG,\"html: \" + inputLine);
}
in.close();
} catch (Exception e) {
e.printstacktrace();
Log.d(LOG_TAG,\"Error: \" + e.getMessage());
Log.d(LOG_TAG,\"HTML CODE: \" + htmlCode);
}
解决方法
您可以使用Runnable或Thread,但可能最惯用的Android方法是使用AsyncTask。
new AsyncTask<String,Void,String>(){
@Override
protected String doInBackground(String... urlStr){
// do stuff on non-UI thread
StringBuffer htmlCode = new StringBuffer();
try{
URL url = new URL(urlStr[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG,\"html: \" + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG,\"Error: \" + e.getMessage());
Log.d(LOG_TAG,\"HTML CODE: \" + htmlCode);
}
return htmlCode.toString();
}
@Override
protected void onPostExecute(String htmlCode){
// do stuff on UI thread with the html
TextView out = (TextView) findViewById(R.id.out);
out.setText(htmlCode);
}
}.execute(\"http://www.google.com\");