android 4.0下訪問主進程訪問網絡和開啓另外另外的線程

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

加上這句話以後 在onCreate方法上加@SuppressLint("NewApi") @Override

另外一種是啓動線程執行下載任務:
android

    public void onCreate(Bundle savedInstanceState) { 網絡

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // 啓動線程執行下載任務
        new Thread(download).start();
    }
   
    /**
     * 下載線程
     */
    Runnable download = new Runnable(){ ide

  @Override
       public void run() {

            Looper.prepare(); 

             download();

             Looper.loop(); 

      }
    }; oop

啓動線程必定要加上Looper.prepare();方法完以後加上Lopper.loop(); 不然會報
ui

Can't create handler inside thread that has not called Looper.prepare() 這個異常
相關文章
相關標籤/搜索