Android软件自动更新实现代码
程序员文章站
2024-03-04 17:20:18
如何实现软件自动更新,下面是具体实例:
效果图:
具体步骤:...
如何实现软件自动更新,下面是具体实例:
效果图:
具体步骤:
1、在服务器上部署更新所用的xml文件:version.xml
<update> <version>2</version> <name>baiduxinwen.apk</name> <url>http://gdown.baidu.com/data/wisegame/e5f5c3b8e59401c8/baiduxinwen.apk</url> </update>
2、在客户端实现更新操作
涉及到三个技术:
1.xml文件的解析
2.httpurlconnection连接
3.文件流i/o
这里创建一个解析xml文件的服务类:parxmlservice.java
package com.xiaowu.news.update; import java.io.inputstream; import java.util.hashmap; import javax.xml.parsers.documentbuilder; import javax.xml.parsers.documentbuilderfactory; import org.w3c.dom.document; import org.w3c.dom.element; import org.w3c.dom.node; import org.w3c.dom.nodelist; public class parsexmlservice { public hashmap<string, string> parsexml (inputstream instream) throws exception{ hashmap<string, string> hashmap = new hashmap<string, string>(); //创建documentbuilderfactory,该对象将创建documentbuilder。 documentbuilderfactory factory = documentbuilderfactory.newinstance(); //创建documentbuilder,documentbuilder将实际进行解析以创建document对象 documentbuilder builder = factory.newdocumentbuilder(); //解析该文件以创建document对象 document document = builder.parse(instream); //获取xml文件根节点 element root = document.getdocumentelement(); //获得所有子节点 nodelist childnodes = root.getchildnodes(); for(int i = 0; i < childnodes.getlength(); i++) { node childnode = (node) childnodes.item(i); if(childnode.getnodetype() == node.element_node) { element childelement = (element) childnode; //版本号 if("version".equals(childelement.getnodename())) { hashmap.put("version", childelement.getfirstchild().getnodevalue()); //软件名称 } else if("name".equals(childelement.getnodename())) { hashmap.put("name", childelement.getfirstchild().getnodevalue()); //下载地址 } else if("url".equals(childelement.getnodename())) { hashmap.put("url", childelement.getfirstchild().getnodevalue()); } } } return hashmap; } }
实现更新操作的管理类:updatemanager.java
package com.xiaowu.news.update; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.net.httpurlconnection; import java.net.malformedurlexception; import java.net.url; import java.util.hashmap; import javax.net.ssl.httpsurlconnection; import android.app.alertdialog; import android.app.alertdialog.builder; import android.app.dialog; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.content.dialoginterface.onclicklistener; import android.content.pm.packagemanager.namenotfoundexception; import android.net.uri; import android.os.environment; import android.os.handler; import android.view.layoutinflater; import android.view.view; import android.widget.progressbar; import android.widget.toast; import com.xiaowu.news.r; /** * * @author wwj * @date 2012/11/17 * 实现软件更新的管理类 */ public class updatemanager { //下载中... private static final int download = 1; //下载完成 private static final int download_finish = 2; //保存解析的xml信息 hashmap<string , string> mhashmap; //下载保存路径 private string msavepath; //记录进度条数量 private int progress; //是否取消更新 private boolean cancelupdate = false; //上下文对象 private context mcontext; //进度条 private progressbar mprogressbar; //更新进度条的对话框 private dialog mdownloaddialog; private handler mhandler = new handler() { public void handlemessage(android.os.message msg) { switch(msg.what){ //下载中。。。 case download: //更新进度条 system.out.println(progress); mprogressbar.setprogress(progress); break; //下载完成 case download_finish: // 安装文件 installapk(); break; } }; }; public updatemanager(context context) { super(); this.mcontext = context; } /** * 检测软件更新 */ public void checkupdate() { if (isupdate()) { //显示提示对话框 shownoticedialog(); } else { toast.maketext(mcontext, r.string.soft_update_no, toast.length_short).show(); } } private void shownoticedialog() { // todo auto-generated method stub //构造对话框 alertdialog.builder builder = new builder(mcontext); builder.settitle(r.string.soft_update_title); builder.setmessage(r.string.soft_update_info); //更新 builder.setpositivebutton(r.string.soft_update_updatebtn, new onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { // todo auto-generated method stub dialog.dismiss(); // 显示下载对话框 showdownloaddialog(); } }); // 稍后更新 builder.setnegativebutton(r.string.soft_update_later, new onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { // todo auto-generated method stub dialog.dismiss(); } }); dialog noticedialog = builder.create(); noticedialog.show(); } private void showdownloaddialog() { // 构造软件下载对话框 alertdialog.builder builder = new builder(mcontext); builder.settitle(r.string.soft_updating); // 给下载对话框增加进度条 final layoutinflater inflater = layoutinflater.from(mcontext); view view = inflater.inflate(r.layout.softupdate_progress, null); mprogressbar = (progressbar) view.findviewbyid(r.id.update_progress); builder.setview(view); builder.setnegativebutton(r.string.soft_update_cancel, new onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { // todo auto-generated method stub dialog.dismiss(); // 设置取消状态 cancelupdate = true; } }); mdownloaddialog = builder.create(); mdownloaddialog.show(); //下载文件 downloadapk(); } /** * 下载apk文件 */ private void downloadapk() { // todo auto-generated method stub // 启动新线程下载软件 new downloadapkthread().start(); } /** * 检查软件是否有更新版本 * @return */ public boolean isupdate() { // 获取当前软件版本 int versioncode = getversioncode(mcontext); //把version.xml放到网络上,然后获取文件信息 inputstream instream = parsexmlservice.class.getclassloader().getresourceasstream("version.xml"); // 解析xml文件。 由于xml文件比较小,因此使用dom方式进行解析 parsexmlservice service = new parsexmlservice(); try { mhashmap = service.parsexml(instream); } catch (exception e) { // todo: handle exception e.printstacktrace(); } if(null != mhashmap) { int servicecode = integer.valueof(mhashmap.get("version")); //版本判断 if(servicecode > versioncode) { return true; } } return false; } /** * 获取软件版本号 * @param context * @return */ private int getversioncode(context context) { // todo auto-generated method stub int versioncode = 0; // 获取软件版本号,对应androidmanifest.xml下android:versioncode try { versioncode = context.getpackagemanager().getpackageinfo( "com.xiaowu.news", 0).versioncode; } catch (namenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } return versioncode; } /** * 下载文件线程 * @author administrator * */ private class downloadapkthread extends thread { @override public void run() { try { //判断sd卡是否存在,并且是否具有读写权限 if (environment.getexternalstoragestate().equals(environment.media_mounted)) { // 获取sdcard的路径 string sdpath = environment.getexternalstoragedirectory() + "/"; msavepath = sdpath + "download"; url url = new url(mhashmap.get("url")); // 创建连接 httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.connect(); // 获取文件大小 int length = conn.getcontentlength(); // 创建输入流 inputstream is = conn.getinputstream(); file file = new file(msavepath); // 如果文件不存在,新建目录 if (!file.exists()) { file.mkdir(); } file apkfile = new file(msavepath, mhashmap.get("name")); fileoutputstream fos = new fileoutputstream(apkfile); int count = 0; // 缓存 byte buf[] = new byte[1024]; // 写入到文件中 do { int numread = is.read(buf); count += numread; // 计算进度条的位置 progress = (int) (((float) count / length) * 100); // 更新进度 mhandler.sendemptymessage(download); if (numread <= 0) { // 下载完成 mhandler.sendemptymessage(download_finish); break; } // 写入文件 fos.write(buf, 0, numread); } while (!cancelupdate);//点击取消就停止下载 fos.close(); is.close(); } } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } // 取消下载对话框显示 mdownloaddialog.dismiss(); } } /** * 安装apk文件 */ private void installapk() { file apkfile = new file(msavepath, mhashmap.get("name")); if (!apkfile.exists()) { return; } intent i = new intent(intent.action_view); i.setdataandtype(uri.parse("file://" + apkfile.tostring()), "application/vnd.android.package-archive"); mcontext.startactivity(i); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。