這個異常大概意思是在主線程訪問網絡時出的異常。 Android在4.0之前的版本 支持在主線程中訪問網絡,但是在4.0以後對這部分程序進行了優化,也就是說訪問網絡的代碼不能寫在主線程中了。
那麼如何做才能正常運行呢? 請看這裏:
例如: 從網絡中獲取一個Url地址。
url = AuthUtil.getAuthorizationURL();
if (url == null) {
Toast.makeText(WebViewActivity.this, R.string.auth_url_empty, 3000).show();
}
如果直接寫在主線程中的話 在2.x 版本中還是能運行 但是在4.0以後就會出現錯誤。
網上也有很多相關資料比如說在主線程中添加
// 詳見StrictMode文檔
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
但是
.detectLeakedClosableObjects() 會報錯,
也就是說這個方法不用,但是查看源碼發現其方法是公共的
/**
* Detect when an {@link java.io.Closeable} or other
* object with a explict termination method is finalized
* without having been closed.
*
* <p>You always want to explicitly close such objects to
* avoid unnecessary resources leaks.
*/
public Builder detectLeakedClosableObjects() {
return enable(DETECT_VM_CLOSABLE_LEAKS);
}
這個我就有點搞不清楚怎麼回事,資歷尚淺還不會。哈哈。
所以我就用第二種方法 也就是多線程,異步加載的方式加載數據。
代碼如下:
在主函數中發送一個空的消息 :
new Thread(){
@Override
publicvoid run() {
// TODO Auto-generated method stub
super.run();
url = AuthUtil.getAuthorizationURL();
if (url == null) {
Toast.makeText(WebViewActivity.this, R.string.auth_url_empty, 3000).show();
}
handler.sendEmptyMessage(0);
}
}.start();
在handler中接受到消息 作出相應的處理。
private Handler handler = new Handler() {
publicvoid handleMessage(Message msg) {
switch (msg.what) {
case0:
<span style="white-space:pre"> </span>load(url, webView);
break;
}
};
};
這樣就解決的這個異常。
有什麼不對的地方,請多指教。