android自动安装sd卡中,Android版本更新下载apk文件到sd卡并自动安装

版本更新,需要注意的是android7.0和8.0的安装问题

android8.0以上得需要安装未知来源应用的权限

android7.0

1.android7.0需要在清单文件注册

2.在res文件下新建xml文件夹,编写file_paths:

下载安装apk的代码:

private void downLoadApk(final String downURL, final String appName){

final ProgressDialog pd = new ProgressDialog(this);

//必须一直下载完,不可取消

pd.setCancelable(false);

pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

pd.setMessage("正在下载安装包");

// pd.setTitle("版本更新");

pd.show();

Thread t = new Thread(){

@Override

public void run() {

try {

File file = downloadFile(downURL, appName, pd);

sleep(1000);

// 结束掉进度条对话框

pd.dismiss();

if (file!=null){

installApk(file);

} else {

Toast.makeText(BrowserActivity.this, "更新包无法下载", Toast.LENGTH_LONG).show();

}

} catch (Exception e) {

pd.dismiss();

}

}

};

t.start();

}

private File downloadFile(String path,String appName ,ProgressDialog pd) throws Exception {

// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

// 获取到文件的大小

pd.setMax(conn.getContentLength());

InputStream is = conn.getInputStream();

String fileName = Environment.getExternalStorageDirectory()+ "/cuair/" + appName+".apk";

File file = new File(fileName);

// 目录不存在创建目录

if (!file.getParentFile().exists()) {

file.getParentFile().mkdirs();

}

FileOutputStream fos = new FileOutputStream(file);

BufferedInputStream 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;

// 获取当前下载量

pd.setProgress(total);

}

fos.close();

bis.close();

is.close();

return file;

} else {

return null;

}

}

/**

* 安装apk

*/

private void installApk(File file) {

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

Log.d("installApk", "版本大于 N ,开始使用 fileProvider 进行安装");

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

Uri contentUri = FileProvider.getUriForFile(this, "com.jetair.cuair.fileprovider", file);

intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

} else {

Log.d("installApk", "正常进行安装");

intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

}

startActivity(intent);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值