異常處理-android.os.NetworkOnMainThreadException

 在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();
		}
    };




發佈了20 篇原創文章 · 獲贊 3 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章