package com.example.weatherdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
TextView tv_content;
TextView tv_info;
long days;
String dates;
TextView tv_date;
Button btn_ok;
InputStream is;
BufferedReader br;
StringBuffer sb = new StringBuffer();
// 发送信息,处理信息
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0x01:
tv_info.setVisibility(View.GONE);
tv_content.setText(sb);
break;
case 2:
tv_date.setText(dates);
break;
default:
break;
}
};
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findView();
btn_ok.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Thread t = new Thread() {
public void run() {
synchronized (this) {
try {
// 准备网址
URL url = new URL(
"http://www.weather.com.cn/data/sk/101010100.html");
// 打开连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 建立连接
urlConn.connect();
if (urlConn.getResponseCode() == 200) {
is = urlConn.getInputStream();
br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
sleep(5000);
mHandler.sendEmptyMessage(0x01);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
}
});
new Thread() {
public void run() {
synchronized (this) {
while (true) {
try {
Date date = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat(
"yyyy年MM月dd日E HH时mm分ss秒");
dates = dateformat.format(date);
Message msg = new Message();
mHandler.sendEmptyMessage(2);
Thread.sleep(1000);
} catch (InterruptedException e) { // TODO
e.printStackTrace();
}
}
}
}
}.start();
}
/**
* 绑定控件
*/
public void findView() {
tv_content = (TextView) findViewById(R.id.tv_content);
tv_info = (TextView) findViewById(R.id.tv_info);
tv_date = (TextView) findViewById(R.id.tv_date);
btn_ok = (Button) findViewById(R.id.btn_ok);
}
}
|
|