java 安卓。操作系统。NetworkOnMainThreadException问题
我想在我的Android应用程序中打开一个socket,从服务器读取文件
我让服务器与模拟器在同一台计算机上运行,我在Android外部进行了测试,以确保连接时没有防火墙问题或其他问题
下面是我遇到问题的代码。它将打印IP地址,后跟streamm000。此时,它抛出一个安卓.os.NetworkOnMainThreadException
另外,另一个toast
给了我NULL
我的代码是
toast("IP="+getIP());
try {
toast("created stream00000");
so=new Socket("10.50.1.25", 80);
toast("created stream111111");
oos=new ObjectOutputStream(so.getOutputStream());
toast("created stream2222");
dos=new DataOutputStream(so.getOutputStream());
//oos.close();
toast("created stream33333");
}
catch(Exception e){
toast(e.getCause() +"problem with this bla bla is opensteam");
toast(e.getMessage()+"problem with this bla bla is opensteam");
Log.v(e+"problem ","with this bla bla is opensteam");
}
# 1 楼答案
您的代码无法回答您的问题。但看起来您正在主UI线程上执行网络操作。这在较新的API级别中是不允许的。当您尝试执行此操作时,它将抛出此异常
您将需要生成一个不同的线程,并在那里执行网络操作
# 2 楼答案
抛出
NetworkOnMainThreadException
是因为在蜂窝状和更高版本中,您必须在与主显示器Thread
分离的线程上执行网络操作请参见此处的描述http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
因此,我的建议是将代码移动到一个新的
Runnable
类中,然后创建一个Thread
来执行它