package com.example.example0803;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Activity01 extends ActionBarActivity {
TextView show_view;
String resultDate;
Handler m_handler=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
fresh();
}
};
Thread m_thread= new Thread() {
public void run(){
while(true){
try {
sleep(5*1000);
m_handler.sendMessage(m_handler.obtainMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity01);
show_view=(TextView) findViewById(R.id.showDate);
fresh();
m_thread.start();
}
public void fresh(){
String
str_url="http://192.168.33.179:8080/liuning/date.jsp";
try {
URL url=new URL(str_url);
try {
HttpURLConnection conn=(HttpURLConnection)
url.openConnection();
conn.connect();
InputStreamReader inReader=new
InputStreamReader(conn.getInputStream());
BufferedReader buffered=new BufferedReader(inReader);
String temp=buffered.readLine();
resultDate="";
while(temp!=null){
resultDate+=temp;
temp=buffered.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
show_view.setText(resultDate);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.activity01, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar
will
// automatically handle clicks on the Home/Up button, so
long
// as you specify a parent activity in
AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
遇到的问题和总结:
1.又忘记在manifest.xml中添加联网权限了
2.不能在子线程中调用fresh()方法,即不能在子线程中更新view的状态,只能在创建这些view的线程中维护和更新view
3.handler是在主线程中的