NetworkOnMainThreadException
從文件 :
應用程式嘗試在其主執行緒上執行網路操作時引發的異常。
僅針對 Honeycomb SDK 或更高版本的應用程式進行此操作。針對早期 SDK 版本的應用程式可以在其主要事件迴圈執行緒上進行聯網,但是非常不鼓勵這樣做。
以下是可能導致該異常的程式碼片段示例:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri.Builder builder = new Uri.Builder().scheme("http").authority("www.google.com");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL(builder.build().toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
} catch (IOException e) {
Log.e("TAG","Connection error", e);
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("TAG", "Error closing stream", e);
}
}
}
}
}
當應用程式嘗試在主執行緒上執行網路操作時,上面的程式碼將為針對 Honeycomb SDK(Android v3.0)或更高版本的應用程式丟擲 NetworkOnMainThreadException
。
要避免此異常,你的網路操作必須始終通過 AsyncTask
,Thread
,IntentService
等在後臺任務中執行。
private class MyAsyncTask extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String[] params) {
Uri.Builder builder = new Uri.Builder().scheme("http").authority("www.google.com");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL(builder.build().toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
} catch (IOException e) {
Log.e("TAG","Connection error", e);
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("TAG", "Error closing stream", e);
}
}
}
return null;
}
}