最近项目刚做完1.2,1.2要上线1.0中写了应用更新代码,不过之前考虑不太全面,Android6.0不能直接跟新,原因把下载的APK要存储到SD卡中,需要获取存储权限。针对这个问题有两种解决方案,第一种是targetSdkVersion 22 就是targetSdkVersion小于23就行,但是之前版本写的23,上线之后在应用商店下载不能直接覆盖,得把之前卸载,感觉体验并不好;第一种是加上获取全下的代码。谢天谢地幸好之前没推广用户量并不多,要不然就该倒霉了,哎呦。话不多说,来干活
public class UpdateData {
/**
* 版本号
* */
private String serverVersion;
/**
*下载地址
* */
private String apkUrl;
/**
* 版本号
* */
private String updateDescription;
/**
* 是否需要强制升级
* */
private boolean forceUpgrade;
public String getServerVersion() {
return serverVersion;
}
public void setServerVersion(String serverVersion) {
this.serverVersion = serverVersion;
}
public String getApkUrl() {
return apkUrl;
}
public void setApkUrl(String apkUrl) {
this.apkUrl = apkUrl;
}
public String getUpdateDescription() {
return updateDescription;
}
public void setUpdateDescription(String updateDescription) {
this.updateDescription = updateDescription;
}
public boolean isForceUpgrade() {
return forceUpgrade;
}
public void setForceUpgrade(boolean forceUpgrade) {
this.forceUpgrade = forceUpgrade;
}
}
public class MainActivity extends Activity {
private Button btn;
private UpdateManager mUpdateManager;
/**
* 从服务器获取的版本号
*/
private String serverVersion = "1.0.1";
/**
* 客户端当前的版本号
*/
private String clientVersion = "1.0";
UpdateData data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
data = new UpdateData();
data.setServerVersion(serverVersion);
data.setApkUrl("http://file.anruan.com/soft/6/chenggua_27951.apk");
data.setUpdateDescription("更新说明:\n1.新增工作台模块\n2.新增门店选择\n3.新增顾问角色\n4.新增潜客功能\n5.新增合约功能\n6.新增统计功能问题");
data.setForceUpgrade(false);
checkUpdate(data);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkUpdate(data);
}
});
}
public void checkUpdate(UpdateData updateBean) {
if (updateBean != null) {
}
//比较版本号
VersionComparator versionComparator = new VersionComparator();
int flag = versionComparator.compare(clientVersion, serverVersion);
if (flag != -1) {
} else {
mUpdateManager = new UpdateManager(
MainActivity.this,
updateBean
);
}
}
}
public class UpdateManager {
private Context mContext;
/**
* 下载地址
*/
private String apkUrl;
/**
* apk保存到SD卡的路径
*/
private static final String savePath = "/sdcard/GPF/";
/**
* 完整路径名
*/
private static final String saveFileName = savePath + "gpf.apk";
/**
* 下载进度条控件
*/
private ProgressBar mProgress;
/**
* 表示正在下载
*/
private static final int DOWNLOADING = 1;
/**
* 下载完毕
*/
private static final int DOWNLOADED = 2;
/**
* 下载失败
*/
private static final int DOWNLOAD_FAILED = 3;
/**
* 下载进度
*/
private int progress;
/**
* 取消下载标志位
*/
private boolean cancelFlag = false;
/**
* 从服务器获取的版本号
*/
private double serverVersion = 1.0;
/**
* 客户端当前的版本号
*/
private double clientVersion = 1.0;
/**
* 更新内容描述信息
*/
private String updateDescription = "";
/**
* 是否强制更新
*/
private boolean forceUpdate = false;
/**
* 表示提示对话框、进度条对话框
*/
private AlertDialog alertDialog1, alertDialog2;
/**
* 构造函数
*
* @param data
*/
public UpdateManager(Context context, UpdateData data) {
this.mContext = context;
//查询当前版本号
// clientVersion = getVersionName();
//获取服务端新版本地址和版本号
apkUrl = data.getApkUrl();
if (data.getUpdateDescription() != null) {
updateDescription = data.getUpdateDescription();
forceUpdate = data.isForceUpgrade();
}
showNoticeDialog();
}
/**
* 显示更新对话框
*/
private Dialog dialog;
public void showNoticeDialog() {
dialog = new Dialog(mContext, R.style.MyDialogStyle);
final Window window = dialog.getWindow();
window.setContentView(R.layout.alert_updata);
TextView title = (TextView) window.findViewById(R.id.tv_msg);
title.setText("更新");
TextView titlec = (TextView) window.findViewById(R.id.tv_msgs);
titlec.setText(updateDescription);
window.findViewById(R.id.im_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView textView = (TextView) window.findViewById(R.id.im_cancel);
if (forceUpdate) {
textView.setVisibility(View.GONE);
} else {
textView.setVisibility(View.VISIBLE);
}
window.findViewById(R.id.im_confirm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkPermissionsWRITE(new RxPermissions((Activity) mContext), new TaskReviewDetailContract.RxPermissionsListener() {
@Override
public void onSuccess() {
dialog.dismiss();
showDownloadDialog();
}
@Override
public void onFail() {
}
});
}
});
dialog.show();
}
public void checkPermissionsWRITE(RxPermissions rxPermissions, final TaskReviewDetailContract.RxPermissionsListener listener) {
rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.subscribe(new Consumer() {
@Override
public void accept(@NonNull Boolean aBoolean) throws Exception {
if (aBoolean) {
listener.onSuccess();
} else {
listener.onFail();
}
}
});
}
/**
* 显示进度条对话框
*/
public void showDownloadDialog() {
final Dialog dialog = new Dialog(mContext, R.style.MyDialogStyle);
final Window window = dialog.getWindow();
window.setContentView(R.layout.alert_download);
mProgress = (ProgressBar) window.findViewById(R.id.update_progress);
//如果是强制更新,则不显示取消按钮
window.findViewById(R.id.img_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
cancelFlag = false;
}
});
TextView textView = (TextView) window.findViewById(R.id.img_cancel);
if (forceUpdate) {
textView.setVisibility(View.GONE);
} else {
textView.setVisibility(View.VISIBLE);
}
dialog.show();
//下载apk
downloadAPK();
}
/**
* 下载apk的线程
*/
public void downloadAPK() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
String apkFile = saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
//缓存流提高读取效率
BufferedInputStream bis=new BufferedInputStream(is);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int count = 0;
byte buf[] = new byte[1024];
//点击取消就停止下载.
int numread=0;
while ((numread =bis.read(buf))!=-1&&!cancelFlag){
count += numread;
progress = (int) (((float) count / length) * 100);
//更新进度
mHandler.sendEmptyMessage(DOWNLOADING);
bos.write(buf, 0, numread);
bos.flush();
}
/**
*numread == -1说明信息已经读取完成 不知道的同学可以看看java IO
*/
if (numread == -1) {
//下载完成通知安装
mHandler.sendEmptyMessage(DOWNLOADED);
}
// do {
// int numread =is.read(buf);
//
// count += numread;
// progress = (int) (((float) count / length) * 100);
// //更新进度
// mHandler.sendEmptyMessage(DOWNLOADING);
// if (numread == -1) {
// //下载完成通知安装
// mHandler.sendEmptyMessage(DOWNLOADED);
// break;
// }
// fos.write(buf, 0, numread);
// } while (!cancelFlag);
bos.close();
bis.close();
} catch (Exception e) {
mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
e.printStackTrace();
}
}
}).start();
}
/**
* 更新UI的handler
*/
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOADING:
mProgress.setProgress(progress);
break;
case DOWNLOADED:
if (alertDialog2 != null) {
alertDialog2.dismiss();
}
installAPK();
break;
case DOWNLOAD_FAILED:
Toast.makeText(mContext, "网络断开,请稍候再试", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
};
/**
* 下载完成后自动安装apk
*/
public void installAPK() {
File apkFile = new File(saveFileName);
if (!apkFile.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(intent);
}
/**
* 获取当前版本号
*/
private double getVersionName() {
// 获取packagemanager的实例
PackageManager packageManager = mContext.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return Double.parseDouble(packInfo.versionName);
}
}
**这里主要是介绍的一些主要方法 ,布局、版本比较和获取权限代码就不在贴出来了,想了解更多的童鞋可以打开这个链接http://download.csdn.net/download/u012941592/10037918