文章目錄
最近測試程式在手機端測試正常,在連網的時候總會拋出android.os.NetworkOnMainThreadException這個異常
也就是說不能在主線程中執行連網操作
在4.0中,訪問網路不能在主程式中進行,有兩個方法可以解決,一個是在主程式中增加:
StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.
// 詳見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());
另一種是啟動線程執行下載任務:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 啟動線程執行下載任務
new Thread(downloadRun).start();
}
/**
* 下載線程
*/
Runnable downloadRun = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
updateListView();
}
};