android 新版本下载 安装

来源:互联网 发布:ubuntu挂载硬盘到data 编辑:程序博客网 时间:2024/04/30 20:13

1 首先在程序启动的时候 向服务器发送请求 服务器会返回    String  newVerString="2|app.quannaojiaoyu.com......"

2 然后根据 “|”拆分为俩个list 元素   取第一个list 元素 和当前的版本号进行比较 如果此元素大于版本号 则发现新版本开始下载 url 为list的第二个元素  下载完毕即可安装
   String newVerString = functions.getHttpResponse(
     urlApi + "base.asp", "getVer");
   System.out.println("newString--->"+newVerString);
   Log.d("StartPage", "Check Server.");
   if (newVerString != null)
   {
    ArrayList<String> listVerStrings = functions.splitString(newVerString);
         //得到当前版本号

    int curVersion = functions.getAppVersionName(getApplicationContext());

              
    Log.d("StartPage", listVerStrings.get(0));
    // Check New Version
    if (curVersion < Integer.parseInt(listVerStrings.get(0)))
    {
     Log.d("StartPage", "find new version.");

     try
     {
    
      URL Url = new URL(listVerStrings.get(1));
      URLConnection conn = Url.openConnection();
      conn.connect();
      InputStream is = conn.getInputStream();
      int fileSize = conn.getContentLength();//获取文件长度

      Log.d("StartPage", "new version download start ("
        + String.valueOf(fileSize) + ")...");

      msg = new Message();
      msg.what = UPDATE_NEWVER;
      msg.arg1 = fileSize;
      handler.sendMessage(msg);

      if (fileSize <= 0)return;
      FileOutputStream FOS = new FileOutputStream(strSDPath
        + "/cawords.apk");
      byte buf[] = new byte[1024];
      int downLoadFilePosition = 0;
      int numread;
      while ((numread = is.read(buf)) != -1)
      {
       FOS.write(buf, 0, numread);
       downLoadFilePosition += numread;
       Log.d("StartPage", "new version downloading ("
         + String.valueOf(downLoadFilePosition)
         + ")...");
      
       msg = new Message();
       msg.what = UPDATE_DOWNLOAD;
       msg.arg1 = downLoadFilePosition;
       handler.sendMessage(msg);
      }

      Log.d("StartPage", "New Version Downloaded.");

      Intent intent = new Intent();
      // 安装程序
      intent.setDataAndType(
        Uri.fromFile(new File(strSDPath
          + "/com.quannaojiaoyu.cadict.apk")),
        "application/vnd.android.package-archive");
      startActivity(intent);
      Log.d("StartPage", "New Version Installed.");
      finish();
      System.exit(0);

     } catch (Exception ex)
     {
    
    如何得到当前版本号:

public static int getAppVersionName(Context context)
{
  int versionName = -1;
  try
  {
   PackageManager pm = context.getPackageManager();
   PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
   versionName = pi.versionCode;
   Log.d("versionName ", versionName +"");
  } catch (Exception e)
  {
   Log.e("GET VER", "Exception", e);
  }
  return versionName;
}