Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

小米 Android 4.0 網路請求異常的解法:善用 StrictMode

編輯:關於 Android 程式設計

在 Android 4.0 之後的版本上開發時,若直接在主線程(UI 線程)進行網路連線等耗時操作,系統會出 NetworkOnMainThreadException 這類例外。這是許多人從舊專案移植到新系統時經常遇到的狀況。

一種直覺的做法,是在任何會用到網路的 Activity 的 onCreate() 方法中,透過 StrictMode 放寬相關政策。範例如下:

[java]
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()
        .penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());

這段程式碼的作用,是讓系統在偵測到磁碟讀寫與網路操作時,僅記錄日誌而不中斷執行。

不過要提醒的是,這種做法只是「讓程式跑得下去」,並非最佳實踐。更理想的方案,是把網路請求與資料庫操作移到背景線程(例如 AsyncTask、Thread 或後續的 ExecutorService),避免阻塞 UI 線程而導致畫面卡頓甚至 ANR。StrictMode 的設定值適合用在除錯階段找出效能瓶頸,正式上線前建議還是回歸到正確的非同步設計。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved