【问题标题】:how to handle NetworkOnMainThreadException while reading text from a file which is present on server从服务器上存在的文件中读取文本时如何处理 NetworkOnMainThreadException
【发布时间】:2012-06-06 13:51:02
【问题描述】:

我在尝试从服务器上存在的 .txt 文件中读取文本时遇到 NetworkOnMainThreadException 我该如何解决这个问题 提前致谢。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        TextView tv= new TextView(this);
        TextView tv2 = new TextView(this);



        StringBuilder content = new StringBuilder();


        try {
            URL url = new URL("http://linktomywebsite/textfile.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                content.append(str +"\n");
                tv.setText(content);
            }
            in.close();
        } catch (MalformedURLException e){
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (NetworkOnMainThreadException e){

            tv2.setText("not connecting to server");
            setContentView(tv2);
        }

    };        
    }

【问题讨论】:

    标签: android android-intent android-emulator android-widget


    【解决方案1】:

    自 api 11 起,网络操作在 ui 线程上为 forbidden。您可以使用AsyncTask,在doInBackground 中请求字符串并在onPostExecute 中显示结果

    【讨论】:

      【解决方案2】:

      创建一个新线程并执行繁重的操作,例如从中获取数据...... ans 使用处理程序或异步任务来更新 UI 上的结果

      就像这样 http://www.vogella.com/articles/AndroidPerformance/article.html

      【讨论】:

        【解决方案3】:

        一种解决方案是允许网络操作(尽管不建议这样做)。在 onCreate() 下面添加这个。

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        

        【讨论】:

          猜你喜欢
          • 2014-01-18
          • 1970-01-01
          • 2012-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多