你如何读取文本文件在关闭的Android 4.0.3互联网 [英] how do you read text files off the internet in Android 4.0.3
问题描述
我是一个较新的Android程序员,我想知道如何可以得到4.0.3阅读的文本关闭互联网。我一直在寻找code,让我上主要的例外网络:的http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html并想知道如果任何人都可以给我提供一些示例code来解决这个问题,以供参考我得到了code我想在这里使用:的http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html.非常感谢。
I am a relatively new Android programmer and I was wondering how you could get read text off the internet in 4.0.3. I keep finding code that gives me a Network on Main exception: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html and was wondering if anyone could provide me some sample code to get around this, for reference I got the code I tried to use here: http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html. Thanks a lot.
推荐答案
在蜂窝和冰淇淋三明治(即安卓3.0+),您无法连接到互联网,在主线程(的onCreate()
,的onPause()
, onResume()
等),你必须代替启动一个新线程。为什么这种改变的原因是因为网络操作可以使应用程序等待很长的时间,如果你正在运行他们在主线程,整个应用程序变得没有反应。如果您尝试从主线程连接,Android将抛出一个 NetworkOnMainThreadException
。
In Honeycomb and Ice Cream Sandwich (i.e. Android 3.0+) , you cannot connect to the internet in the main thread (onCreate()
, onPause()
, onResume()
etc.), and you have to instead start a new thread. The reason why this has changed is because network operations can make the app wait for a long time, and if you're running them in the main thread, the whole application becomes unresponsive. If you try to connect from the main thread, Android will throw a NetworkOnMainThreadException
.
要绕过这一点,你可以运行联网code,从一个新的线程,并使用 runOnUiThread()
做的事情在主线程,如更新用户界面。通常情况下,你可以这样做:
To bypass this, you can run networking code from a new thread, and use runOnUiThread()
to do things in the main thread, such as update the user interface. Generally, you can do something like:
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);
}
}
}
}
}
这篇关于你如何读取文本文件在关闭的Android 4.0.3互联网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!