android2.3新增API StrictMode介紹

來源:互聯網
上載者:User

     Google在android2.3中新增了StrictMode API來設定對一個thread的策略(ui線程或者分線程),它主要檢測了讀寫操作,訪問網路,資料庫讀寫等耗時的操作並將其以log或者dialog等形式列印出來。分析這些日誌,我們可以儘快找出程式運行緩慢的原因進而最佳化代碼,避免ANR(Application Not Responding)視窗的出現。

啟用StrictMode 
推薦的使用StrictMode的方式是,在開發階段,開啟它,在發布應用前,關閉它。 
例如:在你的應用中,onCreate():

Java代碼  
  1. public void onCreate() {  
  2.   
  3.    if (DEVELOPER_MODE) {   
  4.        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() //構造StrictMode  
  5.   
  6.                .detectDiskReads() //當發生磁碟讀操作時輸出  
  7.   
  8.                .detectDiskWrites()//當發生磁碟寫操作時輸出  
  9.   
  10.                .detectNetwork()  //訪問網路時輸出,這裡可以替換為detectAll() 就包括了磁碟讀寫和網路I/O  
  11.   
  12.                .penaltyLog()  //以日誌的方式輸出  
  13.   
  14.                .build());  
  15.   
  16.        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
  17.   
  18.                .detectLeakedSqlLiteObjects() //探測SQLite資料庫操作  
  19.   
  20.           .penaltyLog() //以日誌的方式輸出  
  21.   
  22.                .penaltyDeath()  
  23.   
  24.                .build());  
  25.   
  26.    }  
  27.   
  28.    super.onCreate();  
  29.   
  30.    

當觸發策略中的操作時系統會列印出一條StrictMode日誌,格式如下:

Java代碼  
  1. 02-27 10:03:56.122: DEBUG/StrictMode(16210): StrictMode policy violation; ~duration=696 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=23 violation=2   
  2. 02 02-27 10:03:56.122: DEBUG/StrictMode(16210):     at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:745)    

 另外說明兩點:

1.在android2.3版本直接在ui線程中訪問網路會報錯

2.ANR視窗會在程式阻塞或者耗時超過5秒的運算後彈出 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.