从互联网更新textview

时间:2015-04-02 16:30:57

标签: android textview server

我想制作一个从互联网上请求信息的TextView或Imageview,好像它是一个每日更新的新闻报道,我想做类似的事情,但我不知道如何。

我想我应该有一台服务器或其他东西,但有人可以解释我的过程吗?哪个服务器或做什么?

1 个答案:

答案 0 :(得分:0)

 first you need to enable the permission in the android manifest
<uses-permission android:name="android.permission.INTERNET" /> 
than you can use a textView like this
new Thread() {
            @Override
            public void run() {
                String path ="http://host.com/info.txt"; // your webpage with text
                URL u = null;
                try {
                    u = new URL(path);
                    HttpURLConnection c = (HttpURLConnection) u.openConnection();
                    c.setRequestMethod("GET");
                    c.connect();
                    InputStream in = c.getInputStream();
                    final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    in.read(buffer); // Read from Buffer.
                    bo.write(buffer); // Write Into Buffer.

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TextView text = (TextView) findViewById(R.id.TextView1);
                            text.setText(bo.toString());
                            try {
                                bo.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
 }.start();