欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android程序自动更新功能模块的实现方法【附完整demo源码下载】

程序员文章站 2024-03-06 12:58:55
本文实例讲述了android程序自动更新功能模块的实现方法。分享给大家供大家参考,具体如下: 在程序启动的时候检测服务器上有没有对应版本更新,如果有更新,提示用户是否更新...

本文实例讲述了android程序自动更新功能模块的实现方法。分享给大家供大家参考,具体如下:

在程序启动的时候检测服务器上有没有对应版本更新,如果有更新,提示用户是否更新。

在程序启动的时候首先调用更新模块检测服务器上存放的版本号跟当前程序的版本号如果大于当前版本号,弹出更新对话框,如果用户选择更新,则显示当前更新状态,然后替换当前程序。
程序调用版本更新检测:

private updatemanager updateman;
private progressdialog updateprogressdialog;
/** called when the activity is first created. */
@override
public void oncreate(bundle savedinstancestate)
{
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.main);
  //没有判断网路是否连接
  //检查是否有更新
  //如果有更新提示下载
  updateman = new updatemanager(update_testactivity.this, appupdatecb);
  updateman.checkupdate();
}

执行检测版本号以及回调更新提示

下载更新文件等实现:

package update.test;
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 org.json.jsonarray;
import org.json.jsonobject;
import com.trinet.util.nethelper;
import android.content.context;
import android.content.intent;
import android.content.pm.packageinfo;
import android.content.pm.packagemanager.namenotfoundexception;
import android.net.uri;
import android.os.handler;
import android.os.message;
import android.util.log;
  public class updatemanager {
  private string curversion;
  private string newversion;
  private int curversioncode;
  private int newversioncode;
  private string updateinfo;
  private updatecallback callback;
  private context ctx;
  private int progress;
  private boolean hasnewversion;
  private boolean canceled;
  //存放更新apk文件的路径
  public static final string update_downurl = "http://www.baidu.com/update/update_test.apk";
  //存放更新apk文件相应的版本说明路径
  public static final string update_checkurl = "http://www.baidu.com/update/update_verson.txt";
  public static final string update_apkname = "update_test.apk";
  //public static final string update_verjson = "ver.txt";
  public static final string update_savename = "updateapk.apk";
  private static final int update_checkcompleted = 1;
  private static final int update_downloading = 2;
  private static final int update_download_error = 3;
  private static final int update_download_completed = 4;
  private static final int update_download_canceled = 5;
  //从服务器上下载apk存放文件夹
  private string savefolder = "/mnt/innerdisk/";
 //private string savefolder = "/sdcard/";
 //public static final string save_folder =storage. // "/mnt/innerdisk";
 public updatemanager(context context, updatecallback updatecallback) {
  ctx = context;
  callback = updatecallback;
  //savefolder = context.getfilesdir();
  canceled = false;
  getcurversion();
 }
 public string getnewversionname()
 {
  return newversion;
 }
 public string getupdateinfo()
 {
  return updateinfo;
 }
 private void getcurversion() {
  try {
   packageinfo pinfo = ctx.getpackagemanager().getpackageinfo(
     ctx.getpackagename(), 0);
   curversion = pinfo.versionname;
   curversioncode = pinfo.versioncode;
  } catch (namenotfoundexception e) {
   log.e("update", e.getmessage());
   curversion = "1.1.1000";
   curversioncode = 111000;
  }
 }
 public void checkupdate() {
  hasnewversion = false;
  new thread(){
   // ***************************************************************
   /**
    * @by wainiwann
    *
    */
   @override
   public void run() {
    log.i("@@@@@", ">>>>>>>>>>>>>>>>>>>>>>>>>>>getserververcode() ");
    try {
     string verjson = nethelper.httpstringget(update_checkurl);
     log.i("@@@@", verjson
       + "**************************************************");
     jsonarray array = new jsonarray(verjson);
     if (array.length() > 0) {
      jsonobject obj = array.getjsonobject(0);
      try {
       newversioncode = integer.parseint(obj.getstring("vercode"));
       newversion = obj.getstring("vername");
       updateinfo = "";
       log.i("newvercode", newversioncode
         + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
       log.i("newvername", newversion
         + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
       if (newversioncode > curversioncode) {
        hasnewversion = true;
       }
      } catch (exception e) {
       newversioncode = -1;
       newversion = "";
       updateinfo = "";
      }
     }
    } catch (exception e) {
     log.e("update", e.getmessage());
    }
    updatehandler.sendemptymessage(update_checkcompleted);
   };
   // ***************************************************************
  }.start();
 }
 public void update() {
  intent intent = new intent(intent.action_view);
  intent.setdataandtype(
    uri.fromfile(new file(savefolder, update_savename)),
    "application/vnd.android.package-archive");
  ctx.startactivity(intent);
 }
 // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 public void downloadpackage()
 {
  new thread() {
    @override
    public void run() {
     try {
      url url = new url(update_downurl);
      httpurlconnection conn = (httpurlconnection)url.openconnection();
      conn.connect();
      int length = conn.getcontentlength();
      inputstream is = conn.getinputstream();
      file apkfile = new file(savefolder,update_savename);
      if(apkfile.exists())
      {
       apkfile.delete();
      }
      fileoutputstream fos = new fileoutputstream(apkfile);
      int count = 0;
      byte buf[] = new byte[512];
      do{
       int numread = is.read(buf);
       count += numread;
       progress =(int)(((float)count / length) * 100);
       updatehandler.sendmessage(updatehandler.obtainmessage(update_downloading));
       if(numread <= 0){
        updatehandler.sendemptymessage(update_download_completed);
        break;
       }
       fos.write(buf,0,numread);
      }while(!canceled);
      if(canceled)
      {
       updatehandler.sendemptymessage(update_download_canceled);
      }
      fos.close();
      is.close();
     } catch (malformedurlexception e) {
      e.printstacktrace();
      updatehandler.sendmessage(updatehandler.obtainmessage(update_download_error,e.getmessage()));
     } catch(ioexception e){
      e.printstacktrace();
      updatehandler.sendmessage(updatehandler.obtainmessage(update_download_error,e.getmessage()));
     }
    }
  }.start();
 }
 public void canceldownload()
 {
  canceled = true;
 }
 handler updatehandler = new handler()
 {
  @override
  public void handlemessage(message msg) {
   switch (msg.what) {
   case update_checkcompleted:
    callback.checkupdatecompleted(hasnewversion, newversion);
    break;
   case update_downloading:
    callback.downloadprogresschanged(progress);
    break;
   case update_download_error:
    callback.downloadcompleted(false, msg.obj.tostring());
    break;
   case update_download_completed:
    callback.downloadcompleted(true, "");
    break;
   case update_download_canceled:
    callback.downloadcanceled();
   default:
    break;
   }
  }
 };
 public interface updatecallback {
  public void checkupdatecompleted(boolean hasupdate,
    charsequence updateinfo);
  public void downloadprogresschanged(int progress);
  public void downloadcanceled();
  public void downloadcompleted(boolean sucess, charsequence errormsg);
 }
}

需要连接服务器模块:

package com.trinet.util;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.malformedurlexception;
import java.net.uri;
import java.net.url;
import org.apache.http.httpresponse;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.params.coreprotocolpnames;
import org.apache.http.params.httpconnectionparams;
import org.apache.http.params.httpparams;
import android.content.context;
import android.graphics.drawable.drawable;
import android.net.connectivitymanager;
import android.net.networkinfo;
import android.util.log;
public class nethelper {
 public static string httpstringget(string url) throws exception {
  return httpstringget(url, "utf-8");
 }
 /**
  *
  *
  * @param url
  * @return
  */
 public static drawable loadimage(string url) {
  try {
   return drawable.createfromstream(
     (inputstream) new url(url).getcontent(), "test");
  } catch (malformedurlexception e) {
   log.e("exception", e.getmessage());
  } catch (ioexception e) {
   log.e("exception", e.getmessage());
  }
  return null;
 }
 public static string httpstringget(string url, string enc) throws exception {
  // this method for httpconnection
  string page = "";
  bufferedreader bufferedreader = null;
  try {
   httpclient client = new defaulthttpclient();
   client.getparams().setparameter(coreprotocolpnames.user_agent, "android");
    httpparams httpparams = client.getparams();
    httpconnectionparams.setconnectiontimeout(httpparams, 3000);
    httpconnectionparams.setsotimeout(httpparams, 5000);
   httpget request = new httpget();
   request.setheader("content-type", "text/plain; charset=utf-8");
   request.seturi(new uri(url));
   httpresponse response = client.execute(request);
   bufferedreader = new bufferedreader(new inputstreamreader(response
     .getentity().getcontent(), enc));
   stringbuffer stringbuffer = new stringbuffer("");
   string line = "";
   string nl = system.getproperty("line.separator");
   while ((line = bufferedreader.readline()) != null) {
    stringbuffer.append(line + nl);
   }
   bufferedreader.close();
   page = stringbuffer.tostring();
   log.i("page", page);
   system.out.println(page + "page");
   return page;
  } finally {
   if (bufferedreader != null) {
    try {
     bufferedreader.close();
    } catch (ioexception e) {
     log.d("bbb", e.tostring());
    }
   }
  }
 }
 public static boolean checknetworkstatus(context context) {
  boolean result;
  connectivitymanager cm = (connectivitymanager) context
    .getsystemservice(context.connectivity_service);
  networkinfo netinfo = cm.getactivenetworkinfo();
  if (netinfo != null && netinfo.isconnected()) {
   result = true;
   log.i("netstatus", "the net was connected");
  } else {
   result = false;
   log.i("netstatus", "the net was bad!");
  }
  return result;
 }
}

以及提示对话框:

package com.trinet.util;
import java.lang.reflect.field;
import android.app.alertdialog;
import android.app.alertdialog.builder;
import android.content.context;
import android.content.dialoginterface;
import android.content.dialoginterface.onclicklistener;
import android.view.view;
public class dialoghelper {
 public static void alert(context ctx, charsequence title, charsequence message,
   charsequence oktext, onclicklistener oklistener) {
  alertdialog.builder builder = createdialog(ctx, title, message);
  builder.setpositivebutton(oktext, oklistener);
  builder.create().show();
 }
 public static void alert(context ctx, int titleid, int messageid,
   int oktextid, onclicklistener oklistener) {
  alert(ctx, ctx.gettext(titleid), ctx.gettext(messageid), ctx.gettext(oktextid), oklistener);
 }
 public static void confirm(context ctx, charsequence title, charsequence message,
   charsequence oktext, onclicklistener oklistener, charsequence canceltext,
   onclicklistener cancellistener) {
  alertdialog.builder builder = createdialog(ctx, title, message);
  builder.setpositivebutton(oktext, oklistener);
  builder.setnegativebutton(canceltext, cancellistener);
  builder.create().show();
 }
 public static void confirm(context ctx, int titleid, int messageid,
   int oktextid, onclicklistener oklistener, int canceltextid,
   onclicklistener cancellistener) {
  confirm(ctx, ctx.gettext(titleid), ctx.gettext(messageid), ctx.gettext(oktextid), oklistener, ctx.gettext(canceltextid), cancellistener);
 }
 private static alertdialog.builder createdialog(context ctx, charsequence title,
   charsequence message) {
  alertdialog.builder builder = new builder(ctx);
  builder.setmessage(message);
  if(title!=null)
  {
   builder.settitle(title);
  }
  return builder;
 }
 @suppresswarnings("unused")
 private static alertdialog.builder createdialog(context ctx,int titleid, int messageid) {
  alertdialog.builder builder = new builder(ctx);
  builder.setmessage(messageid);
  builder.settitle(titleid);
  return builder;
 }
 public static void viewdialog(context ctx, charsequence title, view view,
   charsequence oktext, onclicklistener oklistener, charsequence canceltext,
   onclicklistener cancellistener) {
 }
 public static void viewdialog(context ctx, int titleid, view view,
   int oktextid, onclicklistener oklistener, int canceltextid,
   onclicklistener cancellistener) {
  viewdialog(ctx, ctx.gettext(titleid), view, ctx.gettext(oktextid), oklistener, ctx.gettext(canceltextid), cancellistener);
 }
 //
 public static void setdialogshowing(dialoginterface dialog, boolean showing)
 {
  try {
   field field = dialog.getclass().getsuperclass().getdeclaredfield("mshowing");
   field.setaccessible(true);
   field.set(dialog, showing);
  } catch (exception e) {
   e.printstacktrace();
  }
 }
}

下面是又更新的话执行回调函数提示用户:

// 自动更新回调函数
updatemanager.updatecallback appupdatecb = new updatemanager.updatecallback()
{
  public void downloadprogresschanged(int progress) {
   if (updateprogressdialog != null
     && updateprogressdialog.isshowing()) {
    updateprogressdialog.setprogress(progress);
   }
  }
  public void downloadcompleted(boolean sucess, charsequence errormsg) {
   if (updateprogressdialog != null
     && updateprogressdialog.isshowing()) {
    updateprogressdialog.dismiss();
   }
   if (sucess) {
    updateman.update();
   } else {
    dialoghelper.confirm(update_testactivity.this,
      r.string.dialog_error_title,
      r.string.dialog_downfailed_msg,
      r.string.dialog_downfailed_btnnext,
      new dialoginterface.onclicklistener() {
       public void onclick(dialoginterface dialog,
         int which) {
        updateman.downloadpackage();
       }
      }, r.string.dialog_downfailed_btnnext, null);
   }
  }
  public void downloadcanceled()
  {
   // todo auto-generated method stub
  }
  public void checkupdatecompleted(boolean hasupdate,
    charsequence updateinfo) {
   if (hasupdate) {
    dialoghelper.confirm(update_testactivity.this,
      gettext(r.string.dialog_update_title),
      gettext(r.string.dialog_update_msg).tostring()
      +updateinfo+
      gettext(r.string.dialog_update_msg2).tostring(),
        gettext(r.string.dialog_update_btnupdate),
      new dialoginterface.onclicklistener() {
       public void onclick(dialoginterface dialog,
         int which) {
        updateprogressdialog = new progressdialog(
          update_testactivity.this);
        updateprogressdialog
          .setmessage(gettext(r.string.dialog_downloading_msg));
        updateprogressdialog.setindeterminate(false);
        updateprogressdialog
          .setprogressstyle(progressdialog.style_horizontal);
        updateprogressdialog.setmax(100);
        updateprogressdialog.setprogress(0);
        updateprogressdialog.show();
        updateman.downloadpackage();
       }
      },gettext( r.string.dialog_update_btnnext), null);
   }
  }
};

要记得给程序添加权限:

<uses-permission android:name="android.permission.internet"></uses-permission>
<uses-permission android:name="android.permission.write_external_storage" />

完整实例代码点击此处本站下载

更多关于android相关内容感兴趣的读者可查看本站专题:《android视图view技巧总结》、《android编程之activity操作技巧总结》、《android操作sqlite数据库技巧总结》、《android操作json格式数据技巧总结》、《android数据库操作技巧总结》、《android文件操作技巧汇总》、《android编程开发之sd卡操作方法汇总》、《android开发入门与进阶教程》、《android资源操作技巧汇总》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。