项目做到版本更新遇到下载和安装 代码记一下
1:文件下载
三个全局变量
FileOutputStream fos = null;
BufferedInputStream bis = null;
InputStream is = null;
下载
public void downloadApktoappDir(String urlstr, String apkname)
throws IOException {
if (apkname == null || "".equals(apkname))
apkname = urlstr.substring(urlstr.lastIndexOf("/") + 1);
urlstr = AiChuXingApplication.ATTR + urlstr;
URL url = null;
try {
url = new URL(urlstr);
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;
Message msg = Message.obtain();
msg.what = 1;
msg.obj = total*100/size;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fos) {
fos.close();
fos = null;
}
if (null != bis) {
bis.close();
bis = null;
}
if (null != is) {
is.close();
is = null;
}
}
}
handler显示下载进度
case 1:
if (null != downloaddialog) {
if (null != emstx) {
if (((Integer)msg.obj).intValue() >=100) {
downloaddialog.dismiss();
downloaddialog = null;
showInstallDialog();
} else {
emstx.setProgress(((Integer)msg.obj).intValue());
}
}
}
break;
2:安装
public void installApkFromLocalPath(String apkname) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://"
+ getApplicationContext().getFilesDir()
.getAbsolutePath() + "/" + apkname),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
3:权限
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.INTERNET" />
备注:下载文件存放在data/data/packagename/file文件夹下,并没有放在SDCARD中
完成