protected void showUpdataDialog() {
downLoadApk();
}
public void downLoadApk() {
final ProgressDialog pd; // 进度条对话框
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下载更新");
pd.setCancelable(false);
pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
}
});
pd.show();
new Thread() {
@Override
public void run() {
try {
File file = getFileFromServer(downloadUrl, pd);
sleep(1000);
installApk(file);
pd.dismiss(); // 结束掉进度条对话框
} catch (Exception e) {
pd.dismiss(); // 结束掉进度条对话框
Message msg = new Message();
Bundle b = new Bundle();
msg.what = 5;
b.putInt("ret", 0);
msg.setData(b);
// handler.sendMessage(msg);
e.printStackTrace();
}
}
}.start();
}
// 安装apk
protected void installApk(File file) {
Intent intent = new Intent();
// 执行动作
intent.setAction(Intent.ACTION_VIEW);
// 执行的数据类型
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//7.0
Uri uriForFile = FileProvider.getUriForFile(UP72Application.getContext(),
"com.up72.football.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uriForFile, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
// intent.setDataAndType(Uri.fromFile(file),
// "application/vnd.android.package-archive");
startActivity(intent);
}
// 从服务端下载apk文件
public File getFileFromServer(String path, ProgressDialog pd)
throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response;
response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
pd.setMax((int) length);// 设置进度条的最大值
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
File file = null;
if (is != null) {
file = new File(Environment.getExternalStorageDirectory(),
"updata.apk");
if (file.exists()) {
file.delete();
}
LogUtil.e("file", "file:" + file.getAbsolutePath());
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
if (length > 0) {
pd.setProgress(count);
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
// 对文件的长度判断下
if (file.length() == length) {
return file;
} else {
deleteFile(file);
return null;
}
}
// 删除文件
public static void deleteFile(File file) {
if (file != null && file.exists() && !file.isDirectory()) {
file.delete();
}
}