2012-01-29 41 views
0

我是一位相对较新的Android程序员,我在想如何从4.0.3中的互联网中获取文本。我一直在寻找能够给我一个Network on Main异常的代码:http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html,并想知道是否有人可以提供一些示例代码来解决这个问题,以供参考,我得到了我在此尝试使用的代码:http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html。非常感谢。在Android 4.0.3中,您如何从互联网中读取文本文件

+0

你添加Internet权限('<使用许可权的android:name = “android.permission.INTERNET对”/>')到你的'AndroidManifest.xml' – Leandros 2012-01-29 04:20:10

回答

3

在Honeycomb和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); 
     } 
     } 
    } 
    } 
} 
+0

我完全相同的尝试,但没有任何成功。我的机器是Working Behind Proxy,目标版本是4.0。获取HTML中的响应,其中显示“CACHE ACCESS DENIED”,当它用作解析它的输入时抛出XMLPullParserException ....我有2.6.5版本的KSOAP。我想知道它是否可能,也许有些建议会非常有帮助。似乎许多问题(如我的)在SO中没有答案。 – iDroid 2012-06-29 13:10:26

0

您需要完成一个HTTP请求。网上有很多例子。尝试here开始。

相关问题