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

Android应用程序更新并下载实例

程序员文章站 2023-11-11 09:02:28
整理文档,搜刮出一个android应用程序更新并下载实例的代码,稍微整理精简一下做下分享。 创建一个新类,名为updatemanager,代码如下: imp...

整理文档,搜刮出一个android应用程序更新并下载实例的代码,稍微整理精简一下做下分享。

创建一个新类,名为updatemanager,代码如下:

import java.io.bufferedreader;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.httpurlconnection;
import java.net.malformedurlexception;
import java.net.url;
import com.af.mobile.r;
import android.app.alertdialog;
import android.app.dialog;
import android.app.alertdialog.builder;
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.os.message;
import android.view.layoutinflater;
import android.view.view;
import android.widget.progressbar;
import android.widget.toast;


public class updatemanager
{private url url=null;
  /* 下载中 */
  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 mprogress;
  private dialog mdownloaddialog;

  private handler mhandler = new handler()
  {
    public void handlemessage(message msg)
    {
      switch (msg.what)
      {
      // 正在下载
      case download:
        // 设置进度条位置
        mprogress.setprogress(progress);
        break;
      case download_finish:
        // 安装文件
        installapk();
        break;
      default:
        break;
      }
    };
  };

  public updatemanager(context context)
  {
    this.mcontext = context;
  }

  public void checkupdate()
  {
    if (isupdate())
    {
      shownoticedialog();
    } else
    {
      
    }
  }

  /**
   * 检查软件是否有更新版本
   * 
   * @return
   */
  private boolean isupdate()
  {
    // 获取当前软件版本
    double versioncode = getversioncode(mcontext);
  
      double servicecode = 1.2;
      // 版本判断
      if (servicecode > versioncode)
      {
        return true;
      }
    
    return false;
  }

  // 获取软件版本号
  
  private double getversioncode(context context)
  {
    double versioncode = 0.0;
    try
    {
      // 获取软件版本号,对应androidmanifest.xml下android:versioncode
      versioncode = (double) context.getpackagemanager().getpackageinfo("com.af.mobile", 0).versioncode;
    } catch (namenotfoundexception e)
    {
      e.printstacktrace();
    }
    return versioncode;
  }

  
   //显示软件更新对话框
  
  private void shownoticedialog()
  {
    alertdialog.builder builder = new builder(mcontext);
    builder.settitle("软件更新");
    string string=download("http://192.168.0.102:9313/daojuserver/uploads/version.xml");//xml的下载地址
    builder.setmessage(string);

    builder.setpositivebutton("更新", new onclicklistener()
    {
      @override
      public void onclick(dialoginterface dialog, int which)
      {
        dialog.dismiss();
        // 显示下载对话框
        showdownloaddialog();
      }
    });
    // 稍后更新
    builder.setnegativebutton("稍后更新", new onclicklistener()
    {
      @override
      public void onclick(dialoginterface dialog, int which)
      {
        dialog.dismiss();
      }
    });
    dialog noticedialog = builder.create();
    noticedialog.show();
  }

  // 显示软件下载对话框
   
  private void showdownloaddialog()
  {
    // 构造软件下载对话框
    alertdialog.builder builder = new builder(mcontext);
    builder.settitle("djfkjd");//提示信息内容
    // 给下载对话框增加进度条
    final layoutinflater inflater = layoutinflater.from(mcontext);
    view v = inflater.inflate(r.layout.softupdate_progress, null);
    mprogress = (progressbar) v.findviewbyid(r.id.update_progress);
    builder.setview(v);
    // 取消更新
    builder.setnegativebutton("取消更新", new onclicklistener()
    {
      @override
      public void onclick(dialoginterface dialog, int which)
      {
        dialog.dismiss();
        // 设置取消状态
        cancelupdate = true;
      }
    });
    mdownloaddialog = builder.create();
    mdownloaddialog.show();
    // 现在文件
    downloadapk();
  }


  private void downloadapk()
  {
    // 启动新线程下载软件
    new downloadapkthread().start();
  }

  private class downloadapkthread extends thread
  {
    @override
    public void run()
    {
      try
      {
        // 判断sd卡是否存在,并且是否具有读写权限
        if (environment.getexternalstoragestate().equals(environment.media_mounted))
        {
          // 获得存储卡的路径
          string sdpath = environment.getexternalstoragedirectory() + "/";
          msavepath = sdpath + "download";
          url url = new url("http://192.168.0.102:9313/daojuserver/uploads/spmobile.apk");//apk下载地址地址
          // 创建连接
          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, "dhfudh");
          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();
    }
  };
  
  private void installapk()
  {
    file apkfile = new file(msavepath, "dhfudh");
    if (!apkfile.exists())
    {
      return;
    }
    // 通过intent安装apk文件
    intent i = new intent(intent.action_view);
    i.setdataandtype(uri.parse("file://" + apkfile.tostring()), "application/vnd.android.package-archive");
    mcontext.startactivity(i);
  }
  public string download(string urlstring)
  {
    stringbuffer sbbuffer=new stringbuffer();
    string line=null;
    bufferedreader buffer=null;
  try {
    url=new url(urlstring);
    httpurlconnection urlconn=(httpurlconnection) url.openconnection();
    buffer=new bufferedreader(new inputstreamreader(urlconn.getinputstream()));
    while((line=buffer.readline())!=null)
    {
      sbbuffer.append(line);
    }
  } catch (exception e) {
    // todo: handle exception
    e.printstacktrace();
  }
  finally
  {
    try {
      buffer.close();
    } catch (exception e2) {
      // todo: handle exception
      e2.printstacktrace();
    }
  }
  return sbbuffer.tostring();
  }
}

在android应用程序main界面

if(isopennetwork())//判断是否有网络
    {
      updatemanager manager = new  updatemanager(main.this);
    // 检查软件更新
    manager.checkupdate();
      
    }

判断移动端是否有网络

private boolean isopennetwork() {
    connectivitymanager connmanager = (connectivitymanager) getsystemservice(context.connectivity_service);
    networkinfo networkinfo = connmanager.getactivenetworkinfo();

    if (networkinfo != null) {
      // 2.获取当前网络连接的类型信息
      int networktype = networkinfo.gettype();
      if (connectivitymanager.type_wifi == networktype) {
        // 当前为wifi网络
      } else if (connectivitymanager.type_mobile == networktype) {
        // 当前为mobile网络
      }
      return connmanager.getactivenetworkinfo().isavailable();
    }

    return false;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。