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

本文介绍了一种无需SD卡即可完成应用程序升级的方法。通过将更新文件下载到应用文件目录并设置为可读权限,使得安装程序能够顺利安装更新。文中提供了具体的下载及安装代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在进行应用开发时,我们的产品需要升级,如果升级的产品放在服务器上我们就需要下载,并进行安装。一般可以选择下载到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卡的条件下也可以顺利的升级自己的应用程序了。









                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值