android.os.NetworkOnMainThreadException

來源:互聯網
上載者:User

標籤:sig   its   http請求   dea   添加   att   原因   this   color   

android.os.NetworkOnMainThreadException

一、出現原因

我把網路讀取資料的操作寫進了主線程

看名字就應該知道,是網路請求在MainThread中產生的異常 

 

二、產生原因

官網解釋

Class Overview

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it‘s heavily discouraged. See the document Designing for Responsiveness.

Also see StrictMode.

https://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html

解釋一下,從Honeycomb SDK(3.0)開始,google不再允許網路請求(HTTP、Socket)等相關操作直接在Main Thread類中,其實本來就不應該這樣做,直接在UI線程進行網路操作,會阻塞UI、使用者體驗相當bad!即便google不禁止,一般情況下我們也不會這麼做吧~

所以,也就是說,在Honeycomb SDK(3.0)以下的版本,你還可以繼續在Main Thread裡這樣做,在3.0以上,就不行了,建議

 

二、解決方案

直接在main Thread 進行網路操作的方法

在發起Http請求的Activity裡面的onCreate函數裡面添加如下代碼:

1 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()2                 .detectDiskReads().detectDiskWrites().detectNetwork()3                 .penaltyLog().build());4         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()5                 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()6                 .penaltyLog().penaltyDeath().build());

 這種方法簡單好用

詳細參考:http://blog.csdn.net/mad1989/article/details/25964495

 

android.os.NetworkOnMainThreadException

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.