how do you read text files off the internet in Android 4.0.3

后端 未结 2 1830
我在风中等你
我在风中等你 2021-01-27 15:41

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 16:13

    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.

    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);
            }
          }
        }
      }
    }
    

提交回复
热议问题