调用Url.OpenStream当Android的NetworkOnMainThreadException [英] Android NetworkOnMainThreadException when calling Url.OpenStream

查看:222
本文介绍了调用Url.OpenStream当Android的NetworkOnMainThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上运行模拟器我的code(4.0.3的Andr​​oid / API 15),当得到这个例外。当打开一个流会抛出异常。错误消息是

I get this exception when running my code on emulator (Android 4.0.3 / API 15). While opening a stream it will throw an exception. Error-message is null.

try {
    String adress        = "xxx";
    URL url              = new URL(adress);
    InputSource source   = new InputSource(url.openStream());

} catch (Exception e) {
    (new TextView).setText("Error: "+e.getMessage());
}

URL仍与仿真器(浏览器)的工作。

URL is still working with the emulator (in browser).

我已经清理项目。

另外互联网连接被允许:

Also Internet connection is allowed:

<uses-permission android:name="android.permission.INTERNET" />

例外: android.os.NetworkOnMainThreadException

推荐答案

绝不会运行网络上的主( UI )线程操作。

Please never run a networking operation on the main (UI) thread .

主要线程用于:


  • 与用户进行交互。

  • 渲染UI组件。

这是任何长时间的操作风险可能你的应用程序与封闭的 ANR 消息。

any long operation on it may risk your app to be closed with ANR message.

看看以下内容:

  • Keeping your application Responsive
  • NetworkOnMainThreadException

您可以轻松地使用的AsyncTask 来执行您的网络操作。

you can easily use an AsyncTask or a Thread to perform your network operations.

下面是关于Android的线程和后台工作有很大的教程:链接

Here is a great tutorial about threads and background work in android: Link

这篇关于调用Url.OpenStream当Android的NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆