//进入程序
UpdateManager um = new UpdateManager(MainActivity.this);
um.checkUpdate(1);
//点击button
UpdateManager um = new UpdateManager(this);
showProgressDialogIntederminate(false);
um.checkUpdate(2);
um.setCallBack(new UpdateManager.CallBack() {
@Override
public void post() {
dismissProgressDialog();
}
});
public class UpdateManager {
public static final String TAG = "UpdateManager";
private Context mContext;
//更新版本信息对象
private int progress = 0;
// 是否终止下载
private boolean isInterceptDownload = false;
private String mDonwloadUrl;
MaterialDialog mdialog;
MaterialDialog mUpdateiDalog;
private Thread mThread;
String mDescription;
private int forceUpdate = 1; //是否强制更新
private int mVersion;
int presentversionCode;
private CallBack callBack;
int numbers;
int select;
private final static String IGNORE_VERSION = "UpdateManager.IGNORE_VERSION";
/**
* 参数为Context(上下文activity)的构造函数
*
* @param context
*/
public UpdateManager(Context context) {
this.mContext = context;
}
public void checkUpdate(int number) {
select = number;
// 从服务端获取版本信息
String url = Urls.UPDATE_VERSION;
RequestParams params = new RequestParams();
params.addQueryStringParameter("", "");
params.addQueryStringParameter("", "");
NetworkUtils.requestUrl(url, params, mHttpCallback);
}
public interface CallBack {
void post();
}
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
public void getCallBack() {
if (callBack != null) {
callBack.post();
}
}
/**
* 提示更新对话框
*
* @param
*/
private void showUpdateDialog() {
mUpdateiDalog = new DialogBuilder(mContext)
.title(R.string.update_version)
.content(mDescription)
.positiveText(R.string.download)
.negativeText(R.string.cancel)
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
materialDialog.dismiss();
}
})
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
materialDialog.dismiss();
// showDownloadDialog();
showDownloadWebView();
}
}).build();
// mUpdateiDalog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// mUpdateiDalog.setCanceledOnTouchOutside(false);
// mUpdateiDalog.setCancelable(false);
mUpdateiDalog.show();
getCallBack();
}
/**
* 提示更新对话框
*
* @param
*/
private void showLoginUpdateDialog() {
mUpdateiDalog = new DialogBuilder(mContext)
.title(R.string.update_version)
.content(mDescription)
.positiveText(R.string.download)
.negativeText(R.string.cancel)
.neutralText(R.string.ignore_update)
.neutralColor(Color.BLACK)
.onNeutral(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
SharedPreferenceUtil.setInt(IGNORE_VERSION, mVersion);
}
})
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
showDownloadWebView();
}
}).show();
// mUpdateiDalog.setCanceledOnTouchOutside(false);
// mUpdateiDalog.setCancelable(false);
getCallBack();
}
private void showDownloadWebView() {
String url = mDonwloadUrl;
// url = "http://a.app.qq.com/o/simple.jsp?pkgname=cn.igoplus.locker";
Intent intent = new Intent();
intent.setClass(mContext, WebViewActivity.class);
intent.putExtra(WebViewActivity.DATA_TITLE, "更新App");
intent.putExtra(WebViewActivity.DATA_URL, url);
if (!(mContext instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
mContext.startActivity(intent);
}
private void showForceUpdateDialog() {
mUpdateiDalog = new DialogBuilder(mContext)
.title(R.string.update_version)
.content(mDescription)
.positiveText(R.string.download)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
materialDialog.dismiss();
// showForceDownloadDialog();
showDownloadWebView();
}
}).build();
// mUpdateiDalog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
mUpdateiDalog.setCanceledOnTouchOutside(false);
mUpdateiDalog.setCancelable(false);
mUpdateiDalog.show();
getCallBack();
}
/**
* 弹出下载框
*/
private void _showDownloadDialog() {
mdialog = new DialogBuilder(mContext)
.title(R.string.now_download)
.progress(false, 100, true)
.contentGravity(GravityEnum.CENTER)
.positiveText(R.string.backstage_download)
.negativeText(R.string.cancel)
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
materialDialog.dismiss();
//终止下载
isInterceptDownload = true;
}
}).show();
mdialog.setCanceledOnTouchOutside(false);
mdialog.setCancelable(false);
//下载apk
downloadApk();
}
private void showForceDownloadDialog() {
mdialog = new DialogBuilder(mContext)
.title(R.string.now_download)
.progress(false, 100, true)
.contentGravity(GravityEnum.CENTER)
.positiveText(R.string.backstage_download)
.show();
mdialog.setCanceledOnTouchOutside(false);
mdialog.setCancelable(false);
//下载apk
downloadApk();
}
/**
* 下载apk
*/
private void downloadApk() {
//开启另一线程下载
Thread downLoadThread = new Thread(downApkRunnable);
downLoadThread.start();
}
/**
* 从服务器下载新版apk的线程
*/
private Runnable downApkRunnable = new Runnable() {
@Override
public void run() {
if (!android.os.Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED)) {
//如果没有SD卡
Builder builder = new Builder(mContext);
builder.setTitle(R.string.hint);
builder.setMessage(R.string.no_sd);
builder.setPositiveButton(R.string.confirm, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
return;
} else {
try {
//服务器上新版apk地址
URL url = new URL(mDonwloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/updateApkFile/");
if (!file.exists()) {
file.mkdir();
}
//下载服务器中新版本软件(写文件)
String apkFile = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/updateApkFile/"
+ "1";
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[10240];
do {
int numRead = is.read(buf);
count += numRead;
//更新进度条
progress = (int) (((float) count / length) * 100);
handler.sendEmptyMessage(1);
if (numRead <= 0) {
//下载完成通知安装
handler.sendEmptyMessage(0);
break;
}
fos.write(buf, 0, numRead);
//当点击取消时,则停止下载
} while (!isInterceptDownload);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
/**
* 声明一个handler来跟进进度条
*/
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
// 更新进度情况
mdialog.setProgress(progress);
// mdialog.incrementProgress(progress);
break;
case 0:
mdialog.dismiss();
// 安装apk文件
installApk();
break;
default:
break;
}
}
};
/**
* 安装apk
*/
private void installApk() {
// 获取当前sdcard存储路径
File apkfile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/updateApkFile/"
+ "1");
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
// 安装,如果签名不一致,可能出现程序未安装提示
i.setDataAndType(Uri.fromFile(new File(apkfile.getAbsolutePath())),
"application/vnd.android.package-archive");
mContext.startActivity(i);
}
private NetworkUtils.NetworkCallback mHttpCallback = new NetworkUtils.NetworkCallback() {
@Override
public void onSucc(String result) {
Response response = new Response(result);
String rtlCode = response.getReturnCode();
if ("HH0000".equalsIgnoreCase(rtlCode)) {
try {
JSONObject data = response.getDatas();
if (data != null) {
JSONObject datas = data.getJSONObject("data");
if (select == 2) {
if (datas == null) {
showMsgUpdateDialog("您目前的版本已是最新版本!");
}
}
mVersion = datas.getIntValue("version");
if (mVersion == -1) {
return;
}
mDonwloadUrl = datas.getString("donwload_url");
mDescription = datas.getString("description");
String intForceUpdate = datas.getString("force_update");
PackageInfo pi = mContext.getPackageManager()
.getPackageInfo(mContext.getPackageName(),
PackageManager.GET_CONFIGURATIONS);
presentversionCode = pi.versionCode;
if (intForceUpdate.equals("Y")) {
if (presentversionCode < mVersion) {
showForceUpdateDialog();
}else{
getCallBack();
if (select == 2) {
Toast.makeText(GoPlusApplication.getApplication(), R.string.update_version_toast, Toast.LENGTH_SHORT).show();
}
}
} else {
if (select == 1) {
if (presentversionCode < mVersion) {
// 如果当前版本号小于服务端版本号,则弹出提示更新对话框
numbers = SharedPreferenceUtil.getInt(IGNORE_VERSION, 0);
if (numbers == mVersion) {
} else {
showLoginUpdateDialog();
//showUpdateDialog();
}
}
} else {
if (presentversionCode >= mVersion) {
getCallBack();
Toast.makeText(GoPlusApplication.getApplication(), R.string.update_version_toast, Toast.LENGTH_SHORT).show();
} else {
showUpdateDialog();
}
}
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// 其他数据段有问题
getCallBack();
showMsgUpdateDialog(response.getErrorMsg());
}
}
@Override
public void onfailed(String msg) {
// showMsgUpdateDialog("网络连接出错,请检查网络!");
getCallBack();
Toast.makeText(GoPlusApplication.getApplication(), R.string.network_exception, Toast.LENGTH_SHORT).show();
}
};
private void showMsgUpdateDialog(String content) {
mUpdateiDalog = new DialogBuilder(mContext)
.title(R.string.update_version)
.content(content)
.positiveText(R.string.confirm)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
mUpdateiDalog.dismiss();
}
}).build();
mUpdateiDalog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
mUpdateiDalog.show();
getCallBack();
}
}
版本更新
最新推荐文章于 2019-05-16 14:58:45 发布