从网站上阅读文字

时间:2012-02-09 20:39:41

标签: android

我使用模拟器并尝试从网站获取文本.warningdialog的错误:“应用程序主要活动有 意外停了下来。请再试一次。“

    public void testr(View view) throws IOException, URISyntaxException 
  {
     URL websiteurl = new URL("http://test...");
     BufferedReader in = new BufferedReader(
        new InputStreamReader(
       websiteurl.openStream()));

   String inputLine;
   AlertDialog alertbox = new AlertDialog.Builder(this).create();
   while ((inputLine = in.readLine()) != null)
   alertbox.setMessage(inputLine.toString());
   in.close();

 alertbox.show();

  }

3 个答案:

答案 0 :(得分:0)

如果您使用的是Android 2.3或更高版本,那么您可能会遇到操作系统杀死在UI线程中执行网络IO的所有进程的情况,就像您在上面的代码段中所做的那样。

将您的网络io置于后台,例如:使用AsyncTask。看看docs for AsyncTask

答案 1 :(得分:0)

            URL url = new URL("website");
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        rbc = in;

使用此

答案 2 :(得分:0)

try {
    // Create a URL for the desired page
    URL url = new URL("mysite.com/thefile.txt");

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}