HttpURLConnection Handler PULL解析数据 listView 版本更新

来源:互联网 发布:Mac用什么浏览器好 编辑:程序博客网 时间:2024/05/09 20:01


1.MainActivity.class

</pre><pre name="code" class="java">
<span style="font-size:18px;">import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import org.xmlpull.v1.XmlPullParser;import android.app.Activity;import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.util.Xml;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.GridView;import android.widget.ListView;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;import com.handmark.pulltorefresh.library.PullToRefreshListView;public class MainActivity extends Activity {private PullToRefreshListView listView;private Button button1;protected static final int SUCEESS = 0;ArrayList<Bean> blist = new ArrayList<Bean>();private MyBase myBase;//使用的是开源中国的apk      private String apkUrl = "http://www.oschina.net/MobileAppVersion.xml";  Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {  if (msg.what == SUCEESS) {@SuppressWarnings("unchecked")ArrayList<Bean> startAnalyze = (ArrayList<Bean>) msg.obj;// 展示到listView上边 数据成功blist.addAll(startAnalyze);if (myBase == null) {myBase = new MyBase(MainActivity.this, blist);listView.setAdapter(myBase);} else {myBase.notifyDataSetChanged();}listView.onRefreshComplete();//停止刷新  }if(msg.what==1){String xml = (String) msg.obj;  jiexiApkData(xml); } };};private Bean bean;private Update update;@SuppressWarnings({ "unchecked", "rawtypes" })@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button1 = (Button) findViewById(R.id.button1);listView = (PullToRefreshListView) findViewById(R.id.listView);listView.setMode(Mode.BOTH);getHttp();listView.setOnRefreshListener(new OnRefreshListener2() {@Overridepublic void onPullDownToRefresh(PullToRefreshBase refreshView) {// TODO Auto-generated method stubgetHttp(); }@Overridepublic void onPullUpToRefresh(PullToRefreshBase refreshView) {// TODO Auto-generated method stubgetHttp();}}); button1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//请求最新版本数据             reguestAPKData();  }});}private void getHttp() {// TODO Auto-generated method stubfinal String path = "http://www.oschina.net/action/api/news_list?catalog=1&pageIndex=0&pageSize=20";new Thread() {public void run() {try {// http://v.juhe.cn/weixin/query?key=您申请的KEY// 0917c812f187b92e025c9b7c2d4e59b5 pnoURL url = new URL(path);HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();openConnection.setConnectTimeout(5000);openConnection.setReadTimeout(5000);int responseCode = openConnection.getResponseCode();if (responseCode == 200) {InputStream inputStream = openConnection.getInputStream();String parseSteam = StreamUtils.parseSteam(inputStream);ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(parseSteam.getBytes());ArrayList<Bean> startAnalyze = startAnalyze(arrayInputStream);//Gson gson = new Gson();//Bean bean = gson.fromJson(parseSteam, Bean.class);// 展示到listView上handler.obtainMessage(SUCEESS, startAnalyze).sendToTarget();}} catch (Exception e) {e.printStackTrace();}};}.start();}// PULL解析数据protected ArrayList<Bean> startAnalyze(InputStream inputStream) {ArrayList<Bean> twestList = new ArrayList<Bean>();try {XmlPullParser newPullParser = Xml.newPullParser();newPullParser.setInput(inputStream, "utf-8");int eventType = newPullParser.getEventType();while (eventType != XmlPullParser.END_DOCUMENT) {String name = newPullParser.getName();switch (eventType) {case XmlPullParser.START_TAG:if ("news".equals(name)) {bean = new Bean();} else if ("title".equals(name)) {bean.setTitle(newPullParser.nextText());} else if ("body".equals(name)) {bean.setBody(newPullParser.nextText());} else if ("author".equals(name)) {bean.setAuthor(newPullParser.nextText());} else if ("authorid".equals(name)) {bean.setAuthorid(newPullParser.nextText());} else if ("pubDate".equals(name)) {bean.setPubDate(newPullParser.nextText());}break;case XmlPullParser.END_TAG:if ("news".equals(name)) {twestList.add(bean);bean = null;}break;default:break;}eventType = newPullParser.next();}} catch (Exception e) {e.printStackTrace();}return twestList;}/**    * 获得本应用的版本信息    */    private void panduanUpdate(){        try {            PackageManager packageManager = this.getPackageManager();            PackageInfo packInfo = packageManager.getPackageInfo(this.getPackageName(), 0);            String versionName = packInfo.versionName;            if(!versionName.equals(update.getVersionName())){                initAlert();            }        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }    }      /**    * 提醒更新的对话框    */    private void initAlert(){        try {            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);            builder.setTitle("软件版本更新");            builder.setMessage(update.getUpdateLog());            builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {                        @Override                        public void onClick(DialogInterface dialog, int which) {                            //点击立即下载更新包                            downLoadApk();                        }            });            builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int which) {                  }            });              AlertDialog alertDialog = builder.create();            alertDialog.show();        } catch (Exception e) {            e.printStackTrace();        }    }      /**    * 从服务器中下载APK    */      protected void downLoadApk() {          final ProgressDialog pd;    //进度条对话框          pd = new  ProgressDialog(MainActivity.this);          pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);          pd.setMessage("正在下载更新");          pd.show();        //进行下载操作        new Thread(){              @Override              public void run() {                  try {                    //下载                    File file = DownLoadManager.getFileFromServer(update.getDownloadUrl(), pd);                      sleep(3000);                    //安装                    installApk(file);                      pd.dismiss(); //结束掉进度条对话框                  } catch (Exception e) {                  }              }}.start();    }    /**    * 安装apk    */      protected void installApk(File file) {          Intent intent = new Intent();          //执行动作          intent.setAction(Intent.ACTION_VIEW);          //执行的数据类型          intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");          startActivity(intent);      }          /**    * 请求apk信息    */    private void reguestAPKData() {        new Thread() {            @Override            public void run() {                try {                    URL url = new URL(apkUrl);                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();                    conn.setConnectTimeout(5000);                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();                    InputStream is = conn.getInputStream();                    byte[] buffer = new byte[1024];                    int len = -1;                    while ((len = is.read(buffer)) != -1) {                        baos.write(buffer, 0, len);                    }                    // Message message = handler.obtainMessage();                  //  message.obj = baos.toString();                    //handler.obtainMessage(1, message);  //不可以这样操作,会报错,这样相当于                        //发了两次message                  handler.obtainMessage(1, baos.toString()).sendToTarget();                                   //                  String xml = baos.toString();//                  String xml = (String) msg.obj;  //                  jiexiApkData(xml);                                } catch (IOException e) {                    e.printStackTrace();                }            }        }.start();    }      /**    * 解析apk    * @param xml    */    private void jiexiApkData(String xml){        try {            XmlPullParser newPullParser = Xml.newPullParser();            ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());            newPullParser.setInput(bais, "utf-8");            int eventType = newPullParser.getEventType();            while (eventType != XmlPullParser.END_DOCUMENT) {                String name = newPullParser.getName();                switch (eventType) {                    case XmlPullParser.START_TAG:                        if ("android".equals(name)) {                            update = new Update();                        } else if ("versionCode".equals(name)) {                            update.setVersionCode(newPullParser.nextText());                        } else if ("versionName".equals(name)) {                            update.setVersionName(newPullParser.nextText());                        } else if ("downloadUrl".equals(name)) {                            update.setDownloadUrl(newPullParser.nextText());                        } else if ("updateLog".equals(name)) {                            update.setUpdateLog(newPullParser.nextText());                        }                        break;                }                eventType = newPullParser.next();            }        } catch (Exception e) {            e.printStackTrace();        }        //判断更新        panduanUpdate();    }  }</span>


2.activity_main.xml

<span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="检测版本更新" />    <com.handmark.pulltorefresh.library.PullToRefreshListView        android:id="@+id/listView"        android:layout_width="fill_parent"        android:layout_height="fill_parent" >    </com.handmark.pulltorefresh.library.PullToRefreshListView></LinearLayout></span>


3.list.xml


<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/tv_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView" />    <TextView        android:id="@+id/tv_nr"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView" /></LinearLayout></span>

4.Bean

<span style="font-size:18px;">public class Bean {private String id;private String title;private String body;private String author;private String pubDate;private String authorid;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getPubDate() {return pubDate;}public void setPubDate(String pubDate) {this.pubDate = pubDate;}public String getAuthorid() {return authorid;}public void setAuthorid(String authorid) {this.authorid = authorid;}public Bean(String id, String title, String body, String author,String pubDate, String authorid) {super();this.id = id;this.title = title;this.body = body;this.author = author;this.pubDate = pubDate;this.authorid = authorid;}public Bean() {super();// TODO Auto-generated constructor stub}}</span>

5.DownLoadManager

<span style="font-size:18px;">import java.io.BufferedInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import android.app.ProgressDialog;import android.os.Environment;/** * 娑撳娴嘺pk閹碉拷閻劎娈戠猾锟� * Created by Administrator on 2016/7/1. */public class DownLoadManager {    public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{        //婵″倹鐏夐惄鍝ョ搼閻ㄥ嫯鐦界悰銊с仛瑜版挸澧犻惃鍓哾card閹稿倽娴囬崷銊﹀閺堣桨绗傞獮鏈电瑬閺勵垰褰查悽銊ф畱        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){            URL url = new URL(path);            HttpURLConnection conn =  (HttpURLConnection) url.openConnection();            conn.setConnectTimeout(5000);            //閼惧嘲褰囬崚鐗堟瀮娴犲墎娈戞径褍鐨�            pd.setMax(conn.getContentLength());            InputStream is = conn.getInputStream();            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");            FileOutputStream fos = new FileOutputStream(file);            BufferedInputStream bis = new BufferedInputStream(is);            byte[] buffer = new byte[1024];            int len ;            int total=0;            while((len =bis.read(buffer))!=-1){                fos.write(buffer, 0, len);                total+= len;                //閼惧嘲褰囪ぐ鎾冲娑撳娴囬柌锟�                pd.setProgress(total);            }            fos.close();            bis.close();            is.close();            return file;        }        else{            return null;        }    }}</span>

6.MyBase

<span style="font-size:18px;">import java.util.ArrayList;import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;public class MyBase extends BaseAdapter {private Context context;private ArrayList<Bean> list;public MyBase(Context context,ArrayList<Bean> list) {// TODO Auto-generated constructor stubthis.context=context;this.list=list;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn 0;}@Overridepublic View getView(int arg0, View convertView, ViewGroup arg2) {// TODO Auto-generated method stubViewHolder holder=null;if(convertView==null){convertView = View.inflate(context, R.layout.list, null);holder=new ViewHolder();holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);holder.tv_nr = (TextView) convertView.findViewById(R.id.tv_nr);convertView.setTag(holder);}else{holder=(ViewHolder) convertView.getTag();}holder.tv_name.setText(list.get(arg0).getTitle());holder.tv_nr.setText(list.get(arg0).getAuthor()+"    "+list.get(arg0).getPubDate());return convertView;}class ViewHolder{TextView tv_name,tv_nr;}}</span>

7.StreamUtils工具类


<span style="font-size:18px;">import java.io.ByteArrayOutputStream;  import java.io.IOException;  import java.io.InputStream;    public class StreamUtils {      public static String parseSteam(InputStream inputStream) {          try {              // 定义一个字节数组输出流              ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();              // 定义一个字节数组              byte[] buffer = new byte[1024];              // 定义初始长度              int len = 0;              while ((len = inputStream.read(buffer)) != -1) {                  // 将读的内容,写到字节数组输出流中                  arrayOutputStream.write(buffer, 0, len);              }              // 将字节输出流转成字符串              return arrayOutputStream.toString("utf-8");              // utf-8 大小写都可以,gbk 必须大写          } catch (IOException e) {              e.printStackTrace();          }          return null;      }  }  </span>


8.b版本更新的Bean Update

<span style="font-size:18px;">/**  *   * Created by Administrator on 2016/7/1.  */  public class Update {      private String versionCode;        private String versionName;        private String downloadUrl;        private String updateLog;        public String getVersionCode() {          return versionCode;      }        public void setVersionCode(String versionCode) {          this.versionCode = versionCode;      }        public String getVersionName() {          return versionName;      }        public void setVersionName(String versionName) {          this.versionName = versionName;      }        public String getDownloadUrl() {          return downloadUrl;      }        public void setDownloadUrl(String downloadUrl) {          this.downloadUrl = downloadUrl;      }        public String getUpdateLog() {          return updateLog;      }        public void setUpdateLog(String updateLog) {          this.updateLog = updateLog;      }  }  </span>



0 0
原创粉丝点击