package zhang.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class http extends Activity {
private Button go;
private TextView web;
private final String DEBUG_TAG="Activity02";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
go=(Button)findViewById(R.id.button1);
web=(TextView)findViewById(R.id.textView1);
go.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
refresh();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
new Thread(mRunnable).start();
}
public void refresh() throws IOException{
String httpurl="http://wap.baidu.com";
String resultData="";
URL url =null;
try{
url= new URL(httpurl);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if(url!=null){
try{
HttpURLConnection urlconn=(HttpURLConnection)url.openConnection();
InputStreamReader in=new InputStreamReader(urlconn.getInputStream());
BufferedReader buffer=new BufferedReader(in);
String inputLine=null;
while(((inputLine=buffer.readLine())!=null)){
resultData+=inputLine+"\n";
}
in.close();
urlconn.disconnect();
if(resultData!=null){
web.setText(resultData);
}else{
web.setText("null");
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
else{
Log.e(DEBUG_TAG,"urlnull");
}
}
private Runnable mRunnable=new Runnable(){
public void run(){
while(true){
try{
Thread.sleep(5000);
mHandler.sendMessage(mHandler.obtainMessage());
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
};
Handler mHandler =new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
try {
refresh();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<ScrollView android:layout_width="fill_parent" android:layout_height="match_parent">
<TextView android:text="@string/hello" android:id="@+id/textView1"
android:scrollHorizontally="true"
android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
</ScrollView>
</LinearLayout>