android下载文件到应用的文件目录并安装

openkk 12年前

在进行应用开发时,我们的产品需要升级,如果升级的产品放在服务器上我们就需要下载,并进行安装。一般可以选择下载到sd卡中进行安装,
但是对于没有sd卡的设备进行安装升级怎么办,
本文提供了一种方法,将下载的文件放到应用文件目录下然后通过设置为Context.MODE_WORLD_READABLE,让安装程序可以有权限安装此文件。
下载代码如下:
path:网络url
apkname:你希望保存的文件名称

 public void downloadApktoappDir(String path,String apkname) throws IOException{        URL url;        FileOutputStream fos = null;        BufferedInputStream bis = null;        InputStream is = null;      try {          url = new URL(path);          HttpURLConnection conn = (HttpURLConnection) url.openConnection();          conn.setConnectTimeout(5000);          // 获取到文件的大小          int size = conn.getContentLength();          is = conn.getInputStream();            fos = openFileOutput(apkname,          Context.MODE_WORLD_READABLE);          bis = new BufferedInputStream(is);          byte[] buffer = new byte[1024];          int len;          int total = 0;            while ((len = bis.read(buffer)) != -1) {                fos.write(buffer, 0, len);                // 获取当前下载量                total += len;            }      } catch (MalformedURLException e) {          // TODO Auto-generated catch block          e.printStackTrace();      } catch (IOException e) {          // TODO Auto-generated catch block          e.printStackTrace();      }finally{          fos.close();          bis.close();          is.close();      }    }

启动安装程序:

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

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

  public void installApkFromLocalPath(String apkname){     Intent intent = new Intent();     intent.setAction(Intent.ACTION_VIEW);     //first method     intent.setDataAndType(     Uri.parse("file://"+getApplicationContext().getFilesDir().getAbsolutePath() + "/" + apkname),     "application/and.android.package-archive");     startActivity(intent);     //second method  //   intent.setDataAndType(  //   Uri.fromFile(  //           new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + apkname)),  //           "application/and.android.package-archive");  //   startActivity(intent);      }
这样就可以实现再没有sd卡的条件下也可以顺利的升级自己的应用程序了。