我是一个相对较新的 Android 程序员,我想知道如何在 4.0.3 中从互联网上读取文本。我一直在寻找给我带来 Network on Main 异常的代码:http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html并想知道是否有人可以为我提供一些示例代码来解决这个问题,作为参考,我得到了我尝试在此处使用的代码:http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html。多谢。
在 Honeycomb and Ice Cream Sandwich(即 Android 3.0+)中,您无法在主线程中连接到互联网(onCreate()
, onPause()
, onResume()
等),并且您必须启动一个新线程。这种情况发生变化的原因是因为网络操作可能会使应用程序等待很长时间,如果您在主线程中运行它们,则整个应用程序将变得无响应。如果你尝试从主线程连接,Android 将抛出一个NetworkOnMainThreadException
.
要绕过这个问题,您可以从新线程运行网络代码,并使用runOnUiThread()
在主线程中做一些事情,例如更新用户界面。一般来说,你可以这样做:
class MyActivity extends Activity {
public onCreate(Bundle savedInstanceState) {
super.onCreate();
// Create thread
Thread networkThread = new Thread() {
@Override
public void run() {
try {
// this is where your networking code goes
// I'm declaring the variable final to be accessible from runOnUiThread
final String result = someFunctionThatUsesNetwork();
runOnUiThread(new Runnable() {
@Override
public void run() {
// this is where you can update your interface with your results
TextView myLabel = (TextView) findViewById(R.id.myLabel);
myLabel.setText(result);
}
}
} catch (IOException e) {
Log.e("App", "IOException thrown", e);
}
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)