我用讀數據這個代碼的HTML頁面中網頁數據,並把中的WebView閱讀的Android
public class MainActivity extends Activity {
public WebView objwebview ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objwebview = (WebView)findViewById(R.id.webView1);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com");
try
{
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder str = new StringBuilder();
while((line = reader.readLine()) != null) {
str.append(line);
}
objwebview.loadData(str.toString(), "text/html", "UTF-8");
}
catch(Exception e)
{
e.printStackTrace();
objwebview.loadData(e.toString(), "text/html", "UTF-8");
}
但是當我跑,我給這個錯誤(「android.os.networkonmainthreadexception」) 我該如何解決這個問題?
除非強制執行,否則無法在主線程中執行網絡IO操作。通過使用上述兩行,您可以讓主線程訪問網絡並執行任何網絡操作。 –
這是*不是一個好的解決方案。特別是,即使它允許您擺脫異常,它也會削弱您的應用程序的用戶界面。所以它基本上就像關掉安全警衛。 –
是的,它會使應用程序掛起等待響應。但在一些獨家案件中仍然有所幫助。這一個是信息。我會高興 – Sayka