下载应用到SD卡并安装

更新软件时要用到将软件下载到SD卡并主动弹出安装界面,就想安卓市场一样,下面总结一个简单的实训过程:
1、检测某个应用是否已经安装了:

public boolean isPkgInstalled(String packageName) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(packageName, 0);
} catch (Exception e) {
return false;
}
return true;
}

只需要一个包名就可以了。如果是更新软件本身就没必要检测安装,只检测版本号就可以了。

2、判断sd卡是否存在:

private boolean isSDcard() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}

如果不存在就没必要下载了。

3、下载并保存到sd卡:

public void down_file(String url) {
try {
String path = "/sdcard/download/";
filename = url.substring(url.lastIndexOf("/") + 1);

URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
fileSize = conn.getContentLength();
if (fileSize <= 0)
throw new RuntimeException(getString(R.string.download_unknow_size));
if (is == null)
throw new RuntimeException("stream is null");
FileOutputStream fos = new FileOutputStream(path + filename);
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0);
do {
int numread = is.read(buf);
if (numread == -1) {
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
sendMsg(1);
} while (true);

sendMsg(2);
is.close();
} catch (Exception ex) {
Log.e("tag", "error: " + ex.getMessage(), ex);
}
}


4、等下载完成了就要启动安装界面:

private void installAPK() {
String fileName = getSDPath() +"/download/"+filename;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
startActivity(intent);
}


其中的sendMsg()方法是用于更新handler的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值