package com.xinchuang.buynow.utility;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import com.xinchuang.buynow.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import static android.support.v4.content.FileProvider.getUriForFile;
public class UpdateManager {
private static final int DOWNLOAD = 1;
private static final int DOWNLOAD_FINISH = 2;
private String mSavePath;
private int progress;
private boolean cancelUpdate = false;
private Context mContext;
private ProgressBar mProgress;
private Dialog mDownloadDialog;
private static String mApkUrl;
private static String mServiceCode;
private static String mUpdateContent;
private String mPackageNameString = "tangdada";
public interface OnUpdateListener {
void onUpdate(boolean isUpdate);
}
private OnUpdateListener mOnUpdateListener;
public void setOnUpdateListener(OnUpdateListener onUpdateListener) {
mOnUpdateListener = onUpdateListener;
}
public void setUpdateParms(String apkUrl, String serviceCode, String updateContent) {
mApkUrl = apkUrl;
String[] strs = mApkUrl.split("/");
String last = strs[strs.length - 1];
int index = last.indexOf(".");
mPackageNameString = last.substring(0, index);
mServiceCode = serviceCode;
mUpdateContent = updateContent;
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
// 正在下载
case DOWNLOAD:
// 设置进度条位置
if (mContext != null) {
mProgress.setProgress(progress);
}
break;
case DOWNLOAD_FINISH:
// 安装文件
if (mContext != null) {
installApk();
}
break;
default:
break;
}
}
};
public UpdateManager(Activity activity) {
this.mContext = activity;
}
public void checkUpdate(boolean showAlreadyNewDlg) {
if(showAlreadyNewDlg) {
showDownloadDialog();
}else {
if (isNeedUpdate()) {
showNoticeDialog();
} else {
//ToastUtils.showShort(mContext, R.string.soft_update_no);
if (mOnUpdateListener != null) {
mOnUpdateListener.onUpdate(false);
}
}
}
}
public boolean isNeedUpdate() {
String versionCode = getVersionCode(mContext);
// float versionCode = 0;
return mServiceCode.compareTo(versionCode) > 0;
}
private String getVersionCode(Context context) {
String versionCode = "0";
try {
String packageName = context.getPackageName();
versionCode = context.getPackageManager().getPackageInfo(
packageName, 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
private void showNoticeDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("更新V" + mServiceCode + "版");
if(mUpdateContent != null) {
builder.setMessage(mUpdateContent);
} else {
builder.setMessage(R.string.soft_update_info);
}
builder.setPositiveButton("取消",
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (mOnUpdateListener != null) {
mOnUpdateListener.onUpdate(false);
}
}
});
builder.setNegativeButton("确定更新",
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDownloadDialog();
}
});
AlertDialog noticeDialog = builder.create();
noticeDialog.setCancelable(false);
noticeDialog.show();
}
private void showDownloadDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.soft_updating);
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// builder.setNegativeButton(R.string.soft_update_cancel,
// new OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
cancelUpdate = true;
if (mOnUpdateListener != null) {
mOnUpdateListener.onUpdate(false);
}
// }
// });
mDownloadDialog = builder.create();
mDownloadDialog.setCancelable(false);
mDownloadDialog.show();
downloadApk();
}
private void downloadApk() {
new downloadApkThread().start();
}
private class downloadApkThread extends Thread {
@Override
public void run() {
try {
String sdpath = getBaseSavePath(mContext) + "/";
mSavePath = sdpath + "download";
URL url = new URL(mApkUrl);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, mPackageNameString);
// Uri contentUri = getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", apkFile);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte buf[] = new byte[1024];
do {
int numread = is.read(buf);
count += numread;
progress = (int) (((float) count / length) * 100);
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0) {
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
fos.write(buf, 0, numread);
} while (!cancelUpdate);
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mDownloadDialog.dismiss();
}
}
private void installApk() {
File apkfile = new File(mSavePath, mPackageNameString);
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
Uri apkUri = getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", apkfile); //与manifest中定义的provider中的authorities="com.xinchuang.buynow.fileprovider"保持一致
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.setDataAndType(apkUri, "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else {
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
"application/vnd.android.package-archive");
}
mContext.startActivity(i);
}
public static String getBaseSavePath(Context context) {
String sdStatus = Environment.getExternalStorageState();
if (sdStatus.equals(Environment.MEDIA_MOUNTED)) {
return Environment.getExternalStorageDirectory().toString();
} else {
return context.getFilesDir().getAbsolutePath();
}
}
}
调用方法
/**
* 自动更新
*/
private void checkUpdate() {
if (mUpdateManager == null) {
mUpdateManager = new UpdateManager(this);
}
RequestParams params = new RequestParams();
params.addBodyParameter("type", "1");
sendData = XutilHttpHelp.sendData(this, Contants.VERSION_CONTROLLER_API, params, new XutilRequestCallBack.XutilHttpListenet() {
@Override
public void onSuccess(String value) {
VersonControllerResponse response = new Gson().fromJson(value, VersonControllerResponse.class);
if (null != response && response.success) {
VersonControllerResponse.AppVersionBean appVersion = response.appVersion;
String versionCode = appVersion.versionCode;
String apkUrl = appVersion.downloadUrl;
int forceUpdate = appVersion.forceUpdate;
String content = appVersion.content;
if (!TextUtils.isEmpty(apkUrl) && !TextUtils.isEmpty(versionCode)) {
boolean ishouw = versionCode.compareTo(getVersionCode()) > 0;
if (ishouw) {
mUpdateManager.setUpdateParms(apkUrl, versionCode, content);
mUpdateManager.checkUpdate(forceUpdate == 1);
}
}
}
}
@Override
public void onError(HttpException ex, String isOnCallback) {
if (null != sendData
) {
sendData.cancel();
}
}
});
}
private String getVersionCode() {
String versionCode = "0";
try {
String packageName = getPackageName();
versionCode = getPackageManager().getPackageInfo(
packageName, 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}