您的位置:首页 > 移动开发 > Android开发

android 更新并安装应用

2015-10-17 10:53 447 查看
使用xutils.jar, android 5.0以上版本使用xutils2.6.14.jar以上版本。

private ProgressDialog progressDialog = null;
//下载更新apk
private void downloadAPK(String url,String version) {
Log.d("下载地址",url);
HttpUtils http = new HttpUtils();
final String path;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
path = "/sdcard/crash/zhuangxiaomi_"+version+".apk";
}else {
showToast("创建文件失败");
return;
}
progressDialog = ProgressDialog.show(context,"下载","正在下载...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.setMax(100);
HttpHandler handler = http.download(url, path,
true, //如果目标文件已经存在,接着未完成的部分继续下载,服务器不支持RANGE时将从新下载
true,//如果从请求返回信息中获取到文件名,下载完成后自动重命名
new RequestCallBack<File>() {

@Override
public void onStart() {
super.onStart();
progressDialog.show();
//                        showToast("开始下载...");
}

@Override
public void onLoading(long total, long current, boolean isUploading) {
super.onLoading(total, current, isUploading);
progressDialog.setProgress((int)current);
}

@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
progressDialog.cancel();
installAPK(path);
}

@Override
public void onFailure(HttpException e, String s) {
if (s.equals("maybe the file has downloaded completely")){
showToast("文件已经下载");
installAPK(path);
}else {
showToast("下载失败");
}
progressDialog.cancel();
}
});

}

//安装apk
private void installAPK(final String path) {
new AlertDialog.Builder(context).setTitle("安装提示")
.setMessage("下载成功是否安装?")
.setNegativeButton("安装", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
openFile(path);
} catch (Exception e) {
showToast("安装包错误");
e.printStackTrace();
}
}
}).setPositiveButton("取消", null).show();
}

//打开文件
private void openFile(String path){
String filename = path;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(filename)),"application/vnd.android.package-archive");
startActivity(intent);
}
new AlertDialog.Builder(context).setTitle("下载提示")
.setMessage("已检测到新版本,是否更新?")
.setNegativeButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
downloadAPK(result.getUrl(), result.getData());
}
}).setPositiveButton("取消", null).show();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: