在android 2.3上設計的下載程序,在android 4.0上運行時報android.os.NetworkOnMainThreadException異常,原來在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());
另一種是啓動線程執行下載任務:
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();
}
};