你如何读取文本文件在关闭的Andr​​oid 4.0.3互联网互联网、文本文件、oid、Andr

2023-09-04 05:22:03 作者:多啦只是个梦

我是一个较新的Andr​​oid程序员,我想知道如何可以得到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);
        }
      }
    }
  }
}