public class UpdateChecker {
// 权限声明
private static String[]PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private static final int REQUEST_EXTERNAL_STORAGE =1;
//TAG
private static final StringTAG ="UpdateChecker";
// 文件分隔符
private static final StringFILE_SEPARATOR ="/";
// 外存sdcard存放路径
private static final StringFILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() +FILE_SEPARATOR +"autoupdate" +FILE_SEPARATOR;
// 下载应用存放全路径
private static final StringFILE_NAME =FILE_PATH +"autoupdate.apk";
// 更新应用版本标记
private static final int UPDARE_TOKEN =0x29;
// 准备安装新版本应用标记
private static final int INSTALL_TOKEN =0x31;
//上下文
private Contextcontext;
//获取的上级信息
private Stringmessage;
// 以华为天天聊hotalk.apk为例
private Stringspec;
// 下载应用的对话框
private Dialogdialog;
private ProgressDialogprogressDialog;
// 下载应用的进度条
private ProgressBarprogressBar;
// 进度条的当前刻度值
private int curProgress;
// 用户是否取消下载
private boolean isCancel;
//版本对比地址
private AppVersionmAppVersion;
public UpdateChecker(Context context) {
this.context = context;
mAppVersion = AppVersion.getInstance();
}
private final Handlerhandler =new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDARE_TOKEN:
// progressBar.setProgress(curProgress);
progressDialog.setProgress(curProgress);
// dialog.setCanceledOnTouchOutside(false);
progressDialog.setCanceledOnTouchOutside(false);
break;
case INSTALL_TOKEN:
installApp();
break;
}
}
};
/**
* 检测应用更新信息
*/
public void checkUpdateInfo() {
Log.i(TAG, "执行检查更新--->");
showNoticeDialog();
}
/**
* 显示提示更新对话框
*/
private void showNoticeDialog() {
verifyStoragePermissions((Activity)context);
message =mAppVersion.getUpdateMessage();
AlertDialog.Builder alertDialog =new AlertDialog.Builder(context);
alertDialog.setTitle("版本更新");
alertDialog.setMessage(message);
alertDialog.setCancelable(false);// 设置点击屏幕Dialog不消失
alertDialog.setPositiveButton("下载", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDownloadDialog();
}
});
alertDialog.setNegativeButton("忽略", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
/**
* 显示下载进度对话框
*/
private void showDownloadDialog() {
progressDialog =new ProgressDialog(context);
progressDialog.setMessage("版本更新中..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setisCancel();
}
});
progressDialog.show();
downloadApp();
// View view = LayoutInflater.from(context).inflate(R.layout.progressbar, null);
// progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
// AlertDialog.Builder builder = new AlertDialog.Builder(context);
// builder.setTitle("软件版本更新中..");
// builder.setView(view);
// builder.setNegativeButton("取消", new OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// setisCancel();
//// isCancel = true;
// }
// });
// dialog = builder.create();
//
// dialog.show();
// downloadApp();
}
private void setisCancel() {
isCancel =true;
}
/**
* 下载新版本应用
*/
private void downloadApp() {
new Thread(new Runnable() {
@Override
public void run() {
URL url =null;
InputStream in =null;
FileOutputStream out =null;
HttpURLConnection conn =null;
spec =mAppVersion.getApkUrl();
// spec="http://192.168.200.189:8080/FamilinkSYS/APP/app-debug.apk";
try {
url =new URL(spec);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
long fileLength = conn.getContentLength();
in = conn.getInputStream();
File filePath =new File(FILE_PATH);
if (!filePath.exists()) {
filePath.mkdir();
}
out =new FileOutputStream(new File(FILE_NAME));
byte[] buffer =new byte[1024];
int len =0;
long readedLength =0l;
while ((len = in.read(buffer)) != -1) {
// 用户点击“取消”按钮,下载中断
if (isCancel) {
break;
}
out.write(buffer, 0, len);
readedLength += len;
curProgress = (int) (((float) readedLength / fileLength) *100);
handler.sendEmptyMessage(UPDARE_TOKEN);
if (readedLength >= fileLength) {
progressDialog.dismiss();
// dialog.dismiss();
// 下载完毕,通知安装
handler.sendEmptyMessage(INSTALL_TOKEN);
break;
}
}
out.flush();
}catch (Exception e) {
e.printStackTrace();
}finally {
if (out !=null) {
try {
out.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if (in !=null) {
try {
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if (conn !=null) {
conn.disconnect();
}
}
}
}).start();
}
/**
* 安装新版本应用
*/
private void installApp() {
File appFile =new File(FILE_NAME);
if (!appFile.exists()) {
return;
}
Intent intent =new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
// 7.0 以上安装方式改变,进行适配
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3 共享的文件
Uri apkUri = FileProvider.getUriForFile(context, "包名", appFile);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// 添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
// 跳转到新版本应用安装页面
intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
/**
* 6.0以上系统,检查权限是否获取
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
}
}
网友评论