该过年了,突然发现我们经常用的版本更新没为大家发布,实在有点说不过去,毕竟也有了十多个关注我的粉丝,虽然不能像抖音那样一下子成为了网络红人,但是我还带努力,走出自己的路。废话不多说,版本更新其实很简单
1.就是获取我们的版本号,因为咱们版本号都是1.0 ,1.0.1 这样类型的,为了方便, 我就改成了这样,毕竟我们获取的是versionCode,versionname是安装的时候显示在安卓手机上的。
versionCode 100
versionName “1.0.0”
2.我们每次进app请求一下后台给的接口,如果后台给的大于自身app版本号,这样就可以更新了(这要你给后台打一个比你现在版本高德包,改一下版本号就行,然后我们就上代码)
loadNewVersionProgress();这个方法里面填写服务器返回的apk下载地址即可:
/**
* 下载新版本程序
* @param uri
*/
private void loadNewVersionProgress(final String uri) {
final ProgressDialog pd; //进度条对话框
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下载更新");
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
pd.setCanceledOnTouchOutside(false);
pd.setProgressNumberFormat("%1d Mb /%2d Mb");//这里设置的是进度条下面显示的文件大小和下载了多
pd.show();
//启动子线程下载任务
new Thread(){
@Override
public void run() {
try {
File file = getFileFromServer(uri, pd);
sleep(3000);
installApk(file);
pd.dismiss(); //结束掉进度条对话框
} catch (Exception e) {
//下载apk失败
e.printStackTrace();
}
}}.start();
}
/**
* 从服务器获取apk文件的代码
* 传入网址uri,进度条对象即可获得一个File文件
* (要在子线程中执行哦)
*/
public static File getFileFromServer(String uri, ProgressDialog pd) throws Exception{
//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
//获取到文件的大小
pd.setMax(conn.getContentLength()/(1024*1024));
InputStream is = conn.getInputStream();
long time= System.currentTimeMillis();//当前时间的毫秒数
File file = new File(Environment.getExternalStorageDirectory(), time+"updata.apk");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len ;
int total=0;
while((len =bis.read(buffer))!=-1){
fos.write(buffer, 0, len);
total+= len;
//获取当前下载量
pd.setProgress(total/(1024*1024));
}
fos.close();
bis.close();
is.close();
return file;
}
else{
return null;
}
}
下载完之后安装,然后会自动跳转到更新后的app
/**
* 安装apk
*/
protected void installApk(File file) {
Intent intent = new Intent();
//执行动作
intent.setAction(Intent.ACTION_VIEW);
//执行的数据类型
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//关键点:
//安装完成后执行打开
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}