从互联网更新 textview
update textview from internet
我想制作一个从 Internet 请求信息的 TextView 或 Imageview,就好像它是每天更新的新闻应用程序一样,我想做类似的事情,但我不知道怎么做。
我想我应该有一个服务器或类似的东西,但有人可以向我解释一下这个过程吗?哪个服务器或做什么?
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();
我想制作一个从 Internet 请求信息的 TextView 或 Imageview,就好像它是每天更新的新闻应用程序一样,我想做类似的事情,但我不知道怎么做。
我想我应该有一个服务器或类似的东西,但有人可以向我解释一下这个过程吗?哪个服务器或做什么?
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();