NetworkOnMainThreadException 的快速修复

Quick fix for NetworkOnMainThreadException(NetworkOnMainThreadException 的快速修复)

本文介绍了NetworkOnMainThreadException 的快速修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行第三方开源程序,抛出NetworkOnMainThreadException.根据 SDK 参考,这仅适用于针对 Honeycomb SDK 或更高版本的应用程序.允许针对早期 SDK 版本的应用程序在其主事件循环线程上进行联网.

在第一阶段,我只想运行程序,而不更改源.因此,我将 AndroidManifesr.xml 中的行从:

<上一页>安卓:targetSdkVersion="15"

到:

<上一页>安卓:targetSdkVersion="10"

但是,这并没有帮助,程序仍然抛出 NetworkOnMainThreadException.我怎样才能使它工作?我正在尝试在 Android Emulation Google API(16 级)上执行该程序.

解决方案

你可以改成:

android:targetSdkVersion="9"

API 10 对应蜂窝,而 9 是姜饼.此行为仅在 API 10 及更高版本中可见.

但是,我建议不要这样做.相反,您应该将任何长时间运行的操作或可能长时间运行的操作移到后台线程中,例如 AsyncTask.

您也可以尝试使用以下方法关闭严格模式:

 StrictMode.ThreadPolicy 策略 = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy(policy);

I need to execute third-party open source program, which throws NetworkOnMainThreadException. According to SDK reference, 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.

On the first stage I just want to run the program, without changing the source. So, I changed the line in AndroidManifesr.xml from:

    android:targetSdkVersion="15"

to:

    android:targetSdkVersion="10"

However, this doesn't help, and program still throws NetworkOnMainThreadException. How can I make this to work? I am trying to execute the program on Android Emulation Google APIs (level 16).

解决方案

You could change it to:

android:targetSdkVersion="9"

API 10 corresponds to honeycomb, while 9 is gingerbread. This behavior is only seen in APIs 10 and above.

However, I would advise against this. Instead, you should move any long running operations, or operations with the possibility of running for long into a background thread, like an AsyncTask.

You could also try to set Strict Mode off using:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

这篇关于NetworkOnMainThreadException 的快速修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:NetworkOnMainThreadException 的快速修复

基础教程推荐