本实例达到的效果是:首先创建一个网页来显示系统当前的时间,然后在Android程序中每隔5秒钟刷新一次视图,已达到实时更新的效果。
首先,创建一个显示系统当前时间的jsp网页文件,代码如下:
<html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <% String type = request.getParameter("par"); String result = new String(type.getBytes("iso-8859-1"),"gb2312"); out.println("<h1>parameters:"+result+"</h1>"); %> </body> </html>
下面通过Http连接来读取网页,每隔5秒钟,程序自己刷新。要实时的从网页获取数据,其实就是吧获取网络数据的代码写到线程中,不停的进行更新。需要说明一点:android中更新视图不能直接在线程中进行,所以这里需要使用handler来实现更新,具体代码如下:
package com.android; 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.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 MainActivity extends Activity { private final String TAG = "MainActivity" ; private TextView textView; private Button button; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.http); textView = (TextView)findViewById(R.id.text); button = (Button)findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { refresh(); } }); new Thread(mRunnable).start(); } //刷新网页显示 private void refresh(){ String httpUrl = "http://127.0.0.1:8080/test/currentDate.jsp"; String result = ""; URL url = null; try{ //构造一个URL对象 url = new URL(httpUrl); }catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException"); e.printStackTrace(); } if(url != null){ try{ //使用httpURLConnection打开连接 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); //得到读取的内容 InputStreamReader inReader = new InputStreamReader(urlConnection.getInputStream()); //为输出创建BufferedReader BufferedReader bufferedReader = new BufferedReader(inReader); String line = null; //使用循环来读取获得的数据 while((line=bufferedReader.readLine())!=null){ result += line +"\n"; } //关闭InputStreamReader inReader.close(); //关闭Http连接 urlConnection.disconnect(); if(result.equals("")){ textView.setText("读取的内容为null"); }else{ textView.setText(result); } }catch (IOException e) { // TODO: handle exception Log.e(TAG, "IOException"); e.printStackTrace(); } }else{ Log.e(TAG, "url null"); } } private Runnable mRunnable = new Runnable() { @Override public void run() { while(true){ try{ Thread.sleep(5 * 1000); //发送消息 handler.sendMessage(handler.obtainMessage()); }catch (InterruptedException e) { // TODO: handle exception Log.e(TAG, "InterruptedException"); e.printStackTrace(); } } } }; Handler handler = new Handler(){ public void handleMessage(Message msg){ super.handleMessage(msg); refresh(); } }; }
注意:代码中的url地址中的ip:127.0.0.1需要修改成自己所需要的地址