目前的項目之中基本上都會存在版本更新的功能聊记,分為強制更新和推薦更新,其實功能點都是一樣的,推薦更新只是增加一個按鈕讓更新的彈框隱藏掉而已狈蚤,這里僅記錄強制更新的功能
首先需要跟接口約定列牺,需要判斷是否彈出更新彈框
val isUpdate = VersionUtils.compareVersions("服務端新的版本號","本地版本號")
if (result.isIsNew && isUpdate) {
//檢查更新
val checkVersionUtils = CheckVersionUtils(this, result.versionPath
, result.versionDesc, result.newVersion)
checkVersionUtils.showUpdateVersion()
}
這里的isNew為true表示有新版本更新整陌,為false則沒有更新,為了防止服務端出錯瞎领,這里加上了本地的版本號和服務端的版本號進行匹配的字段
CheckVersionUtils
public class CheckVersionUtils {
private Context mContext;
private Dialog mDialog;
private TextView tvUpdate, tvProgress;
private ProgressBar progressBar;
private Logger logger = LoggerFactory.getLogger(CheckVersionUtils.class);
//下載地址
private String apkUrl;
private List<String> apkDes;
private String newVersion;
public CheckVersionUtils(Context context, String apkUrl, List<String> apkDes, String newVersion) {
this.mContext = context;
this.apkUrl = apkUrl;
this.apkDes = apkDes;
this.newVersion = newVersion;
}
/**
* 版本更新彈框
*/
@SuppressLint("SetTextI18n")
public void showUpdateVersion() {
mDialog = new Dialog(mContext, R.style.Teldialog);
mDialog.setContentView(R.layout.dialog_update_version);
mDialog.setCanceledOnTouchOutside(false);
mDialog.setCancelable(false);
mDialog.show();
tvUpdate = mDialog.findViewById(R.id.tv_update);
tvProgress = mDialog.findViewById(R.id.tv_progress);
progressBar = mDialog.findViewById(R.id.progress_bar);
TextView tvVersion = mDialog.findViewById(R.id.tv_version);
tvVersion.setText("v" + newVersion);
TextView tvDes = mDialog.findViewById(R.id.tv_des);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < apkDes.size(); i++) {
String des = "· " + apkDes.get(i) + "\n";
stringBuffer.append(des);
}
tvDes.setText(stringBuffer);
//立即更新
tvUpdate.setOnClickListener(view -> {
tvUpdate.setVisibility(View.GONE);
tvProgress.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
initDownload();
});
}
/**
* 下載apk
*/
private void initDownload() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url(apkUrl)
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
logger.error("apk下載失斆诒琛:" + e.getMessage());
apkUrl = apkUrl.replace("https", "http");
initDownload();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
InputStream inputStream = body.byteStream();
saveFile(inputStream, Environment.getExternalStorageDirectory() + "/" + "demo.apk", body.contentLength());
}
});
}
/**
* @param saveFile 存放的地址
* @param fileLength 文件的長度
*/
@SuppressLint("SetTextI18n")
private void saveFile(InputStream inputStream, String saveFile, final long fileLength) {
long count = 0;
try {
FileOutputStream outputStream = new FileOutputStream(new File(saveFile));
int length = -1;
byte[] bytes = new byte[1024 * 10];
while ((length = inputStream.read(bytes)) != -1) {
// 寫入文件
outputStream.write(bytes, 0, length);
count += length;
final long finalCount = count;
((Activity) mContext).runOnUiThread(() -> {
// 設置進度條最大值
progressBar.setMax((int) fileLength);
// 設置下載進度
progressBar.setProgress((int) finalCount);
// 設置進度文本 (100 * 當前進度 / 總進度)
tvProgress.setText((int) (100 * finalCount / fileLength) + "%");
});
}
inputStream.close();
outputStream.close();
((Activity) mContext).runOnUiThread(() -> {
//下載完成,自動安裝
mDialog.dismiss();
((Activity) mContext).finish();
installApk(new File(Environment.getExternalStorageDirectory() + "/" + "demo.apk"));
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 安裝apk文件
*
* @param apkFile 安裝包所在目錄
*/
private void installApk(File apkFile) {
//判斷版本是否在7.0以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext,
"com.carson.fileprovider", apkFile);
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//對目標應用臨時授權該Uri所代表的文件
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.setDataAndType(apkUri, "application/vnd.android.package-archive");
mContext.startActivity(install);
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(install);
}
}
}
需要在manifest中添加處理
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.carson.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
xml下的file_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="files_root"
path="Android/data/com.yugyg.shopkeeper/" />
<external-path
name="external_storage_root"
path="." />
<root-path
name="root_path"
path="" />
</paths>
貼上dialog
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="316dp"
android:layout_height="385dp"
android:background="@mipmap/bg_update"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingStart="12dp"
android:paddingEnd="12dp"
tools:ignore="MissingDefaultResource">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:text="發(fā)現(xiàn)新版本"
android:textColor="@color/color_white"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_title"
android:layout_marginTop="8dp"
android:background="@drawable/bg_tv_version"
android:paddingStart="12dp"
android:paddingTop="4dp"
android:paddingEnd="12dp"
android:paddingBottom="4dp"
android:text="v1.4"
android:textColor="@color/color_white"
android:textSize="12sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<TextView
android:id="@+id/tv_des"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp"
android:lineSpacingMultiplier="1.5"
android:text="111"
android:textColor="@color/color_black"
android:textSize="12sp" />
</android.support.v4.widget.NestedScrollView>
<RelativeLayout
android:layout_width="88dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:layout_marginBottom="20dp">
<TextView
android:id="@+id/tv_update"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_update_version"
android:gravity="center"
android:text="立即更新"
android:textColor="@color/color_white"
android:textSize="12sp" />
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:indeterminateOnly="false"
android:mirrorForRtl="true"
android:progressDrawable="@drawable/progress_drawable"
android:visibility="gone" />
<TextView
android:id="@+id/tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="0%"
android:textColor="@color/color_white"
android:textSize="12sp"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
styles
<style name="Teldialog" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@color/windowTransaction</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:gravity">bottom</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowCloseOnTouchOutside">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:backgroundDimEnabled">true</item>
</style>
到此九默,功能全部實現(xiàn)
實現(xiàn)效果圖
圖片.png
最后貼上版本的比較震放,在后端進行比較后前端最好也進行一次比較,防止錯誤的出現(xiàn)驼修,進行容錯處理
/**
* 如果版本1 大于 版本2 返回true 否則返回fasle 支持 2.2 2.2.1 比較
* 支持不同位數(shù)的比較 2.0.0.0.0.1 2.0 對比
*
* @param newVersion 版本服務器版本 " 1.1.2 "
* @param nowVersion 版本 當前版本 " 1.2.1 "
* @return ture :需要更新 false : 不需要更新
*/
public static boolean compareVersions(String newVersion, String nowVersion) {
//判斷是否為空數(shù)據(jù)
if (TextUtils.equals(newVersion, "") || TextUtils.equals(nowVersion, "")) {
return false;
}
String[] str1 = newVersion.split("\\.");
String[] str2 = nowVersion.split("\\.");
if (str1.length == str2.length) {
for (int i = 0; i < str1.length; i++) {
if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return true;
} else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return false;
} else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
}
}
} else {
if (str1.length > str2.length) {
for (int i = 0; i < str2.length; i++) {
if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return true;
} else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return false;
} else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
if (str2.length == 1) {
continue;
}
if (i == str2.length - 1) {
for (int j = i; j < str1.length; j++) {
if (Integer.parseInt(str1[j]) != 0) {
return true;
}
if (j == str1.length - 1) {
return false;
}
}
return true;
}
}
}
} else {
for (int i = 0; i < str1.length; i++) {
if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return true;
} else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return false;
} else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
if (str1.length == 1) {
continue;
}
if (i == str1.length - 1) {
return false;
}
}
}
}
}
return false;
}