自动下载安装更新程序

Context.MODE_WORLD_READABLE,让安装程序可以有权限安装此文件。
下载代码如下:
path:网络url
apkname:你希望保存的文件名称


[java] view plain copy
  1. publicvoiddownloadApktoappDir(Stringpath,Stringapkname)throwsIOException{
  2. URLurl;
  3. FileOutputStreamfos=null;
  4. BufferedInputStreambis=null;
  5. InputStreamis=null;
  6. try{
  7. url=newURL(path);
  8. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  9. conn.setConnectTimeout(5000);
  10. //获取到文件的大小
  11. intsize=conn.getContentLength();
  12. is=conn.getInputStream();
  13. fos=openFileOutput(apkname,
  14. Context.MODE_WORLD_READABLE);
  15. bis=newBufferedInputStream(is);
  16. byte[]buffer=newbyte[1024];
  17. intlen;
  18. inttotal=0;
  19. while((len=bis.read(buffer))!=-1){
  20. fos.write(buffer,0,len);
  21. //获取当前下载量
  22. total+=len;
  23. }
  24. }catch(MalformedURLExceptione){
  25. //TODOAuto-generatedcatchblock
  26. e.printStackTrace();
  27. }catch(IOExceptione){
  28. //TODOAuto-generatedcatchblock
  29. e.printStackTrace();
  30. }finally{
  31. fos.close();
  32. bis.close();
  33. is.close();
  34. }
  35. }


 

启动安装程序:

apkname:是保存文件时的文件名,

在需要进行升级的地方调用下面函数即可。

[html] view plain copy
  1. publicvoidinstallApkFromLocalPath(Stringapkname){
  2. Intentintent=newIntent();
  3. intent.setAction(Intent.ACTION_VIEW);
  4. //firstmethod
  5. intent.setDataAndType(
  6. Uri.parse("file://"+getApplicationContext().getFilesDir().getAbsolutePath()+"/"+apkname),
  7. "application/and.android.package-archive");
  8. startActivity(intent);
  9. //secondmethod
  10. //intent.setDataAndType(
  11. //Uri.fromFile(
  12. //newFile(getApplicationContext().getFilesDir().getAbsolutePath()+"/"+apkname)),
  13. //"application/and.android.package-archive");
  14. //startActivity(intent);
  15. }

这样就可以实现再没有sd卡的条件下也可以顺利的升级自己的应用程序了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值