android版本更新库,GitHub - xuexiangjys/XUpdate: A lightweight, high availability Android version update f...

XUpdate

68747470733a2f2f6a69747061636b2e696f2f762f7875657869616e676a79732f585570646174652e737667

68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4150492d31342b2d627269676874677265656e2e737667

68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f7875657869616e676a79732f585570646174652e737667

68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f7875657869616e676a79732f585570646174652e737667

A lightweight, high availability Android version update framework. Click instruction document to experience it!

Please read 【wisdom of asking questions】 before raising the issue and strictly follow the issue template fill in and save everyone's time.

Please read the instruction document carefully before use, important things are to be repeated for three time!!!

Please read the instruction document carefully before use, important things are to be repeated for three time!!!

Please read the instruction document carefully before use, important things are to be repeated for three time!!!

About me

68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4769744875622d7875657869616e676a79732d626c75652e73766768747470733a2f2f696d672e736869656c64732e696f2f62616467652f4353444e2d7875657869616e676a79732d677265656e2e73766768747470733a2f2f696d672e736869656c64732e696f2f62616467652f6a69616e7368752d7875657869616e676a79732d7265642e73766768747470733a2f2f696d672e736869656c64732e696f2f62616467652f6a75656a696e2d7875657869616e676a79732d627269676874677265656e2e73766768747470733a2f2f696d672e736869656c64732e696f2f62616467652f7a686968752d7875657869616e676a79732d76696f6c65742e737667

Simplify use

If you want to use xupdate faster, reduce the difficulty of integration, support breakpoint continuation download and other expansion functions, you can try to use XUpdateAPI.

Rapid integration of X-Library

In order to facilitate the rapid integration of X-Library, I provide a template project for your reference: https://github.com/xuexiangjys/TemplateAppProject

Features

It supports Post or Get request to check version, and supports user-defined network requests.

Only version update under WiFi is supported。

Support silent download (background update) and automatic version update.

The user-friendly version update prompt pop-up window is provided to customize the theme style.

It supports user-defined version update checker, parser, prompter, downloader, install listener and error listener.

Support MD5 file verification, version ignore, version forced update and other functions.

It supports the user-defined file verification method【MD5 verification by default】.

Support custom request API interface.

Compatible with Android 6.0, 7.0, 8.0, 9.0 and 10.0.

Support Chinese and English language (internationalization).

Support the use of the flutter plugin:flutter_xupdate。

Support the use of react native plugin:react-native-xupdate。

Composition structure

This framework refers to AppUpdate some ideas and UI, the various parts of the version update are separated to form the following parts:

IUpdateChecker: Check for the latest version.

IUpdateParser: Parsing the data results returned by the server.

IUpdatePrompter: Display the latest version information.

IUpdateDownloader: Download the latest version of APK installation package.

IUpdateHttpService: The interface for network request.

In addition, there are two listeners:

OnUpdateFailureListener: Listening error

OnInstallListener: Callback of application installation

Update core manager:

IUpdateProxy: Responsible for the process control of version update, calling update to start the version update process.

Update process

Process after calling update:

IUpdateProxy/XUpdate --- (update) ---> IUpdateChecker --->(Request the server to get the latest version information)---> IUpdateParser ---> (Parse the data returned by the server, and build the UpdateEntity)---> IUpdateProxy ---> (If there is no latest version, end it directly, otherwise proceed to the following process)

---Automatic mode---> IUpdateDownloader ---> (Download the latest app apk) ---> Install application

---Non automatic mode---> IUpdatePrompter ---> Prompt for version update

---> click Update ---> IUpdateDownloader ---> (Download the latest app apk) ---> Jump to application installation UI

---> Click cancel or ignore ---> End

1、Demonstration

Default version update

f3389b87eb42f445bad49bdfed5b176b.png

Background update

68747470733a2f2f696d672e727275752e6e65742f696d6167652f35663964376237363939303161

Force version update

feefd7655e4b781898563aff478b8574.png

Ignored version update

e7d2a5c32fe16d2e7c5bc64b1ea438a8.png

Custom pop up theme

1300504f92d38976840c835fdbf7b127.png

Use the system pop-up prompt

68747470733a2f2f696d672e727275752e6e65742f696d6167652f35663964376237376162343266

Demo update background service

Because GitHub is slow to visit recently, if you need to experience xupdate better, you can Click to build a simple version update service.

Demo Download

Pgyer Download

Pgyer Download password: xuexiangjys

68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646f776e6c6f6164732d322e314d2d626c75652e737667

68747470733a2f2f696d672e727275752e6e65742f696d6167652f35663764393439383330333265

GitHub Download

68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646f776e6c6f6164732d322e314d2d626c75652e737667

68747470733a2f2f696d672e727275752e6e65742f696d6167652f35663764393439383339333739

2、Quick integration guide

At present, it supports the use of the mainstream development tool AndroidStudio and add dependency by configures build.gradle directly.

2.1、Add gradle dependency

1.In the project root directory build.gradle:

allprojects {

repositories {

...

maven { url "https://jitpack.io" }

}

}

2.Then, in the dependencies of the project:

The following is the version description. Choose one.

androidx project: above 2.0.0

dependencies {

...

// androidx project

implementation 'com.github.xuexiangjys:XUpdate:2.0.7'

}

support project: below 1.1.6

dependencies {

...

// support project

implementation 'com.github.xuexiangjys:XUpdate:1.1.6'

}

2.2、Initialization

Initialize settings at the top of the application:

XUpdate.get()

.debug(true)

.isWifiOnly(true) // By default, only version updates are checked under WiFi

.isGet(true) // The default setting uses Get request to check versions

.isAutoMode(false) // The default setting is non automatic mode

.param("versionCode", UpdateUtils.getVersionCode(this)) // Set default public request parameters

.param("appKey", getPackageName())

.setOnUpdateFailureListener(new OnUpdateFailureListener() { // Set listening for version update errors

@Override

public void onFailure(UpdateError error) {

if (error.getCode() != CHECK_NO_NEW_VERSION) { // Handling different errors

ToastUtils.toast(error.toString());

}

}

})

.supportSilentInstall(true) // Set whether silent installation is supported. The default is true

.setIUpdateHttpService(new OKHttpUpdateHttpService()) // This must be set! Realize the network request function.

.init(this); // This must be initialized

【note】: if there is any problem, you can open debug mode to track the problem. If you also need to log on disk, you can implement the following interface.

XUpdate.get().setILogger(new ILogger() {

@Override

public void log(int priority, String tag, String message, Throwable t) {

// Realize the function of logging

}

});

2.3、Version update entity information

(1) UpdateEntity

Field name

Type

Default value

Description

mHasUpdate

boolean

false

Whether have the latest version

mIsForce

boolean

false

Force installation: app cannot be used without installation

mIsIgnorable

boolean

false

Whether the version can be ignored

mVersionCode

int

0

Latest version code

mVersionName

String

unknown_version

Latest version name

mUpdateContent

String

""

Update content

mDownloadEntity

DownloadEntity

Download information entity

mIsSilent

boolean

false

Whether to download silently: when there is a new version, do not prompt to download directly

mIsAutoInstall

boolean

true

Whether to automatic install app when the download is completed

(2) DownloadEntity

Field name

Type

Default value

Description

mDownloadUrl

String

""

Download address

mCacheDir

String

""

File download directory

mMd5

String

""

The encrypted check value of the downloaded file (MD5 encryption is used by default), which is used to verify and prevent the downloaded APK file from being replaced (the latest demo has a tool for calculating the check value). Note that the MD5 value here is not the MD5 value of the application signature file!

mSize

long

0

Size of download file【unit: KB】

mIsShowNotification

boolean

false

Whether to show download progress in the notification bar

(3) PromptEntity

Field name

Type

Default value

Description

mThemeColor

int

R.color.xupdate_default_theme_color

Theme colors (background colors for progress bars and buttons)

mTopResId

int

R.drawable.xupdate_bg_app_top

Top background image resource ID

mButtonTextColor

int

0

Button text color

mSupportBackgroundUpdate

boolean

false

Whether background updates are supported

mWidthRatio

float

-1(Unconstrained)

The ratio of the width of the version update prompter to the screen

mHeightRatio

float

-1(Unconstrained)

The ratio of the height of the version update prompter to the screen

2.4、File encryption verification method

The default file encryption verification method used in this framework is MD5 encryption. Of course, if you don't want to use MD5 encryption, you can also customize the File Encryptor IFileEncryptor. The following is the implementation of MD5 File Encryptor for reference:

/**

* The default file encryption calculation uses MD5 encryption

*

* @author xuexiang

* @since 2019-09-06 14:21

*/

public class DefaultFileEncryptor implements IFileEncryptor {

/**

* Encrypted files

*

* @param file

* @return

*/

@Override

public String encryptFile(File file) {

return Md5Utils.getFileMD5(file);

}

/**

* Verify that the file is valid (whether the encryption is consistent)

*

* @param encrypt The encrypted value, is considered to be valid if encrypt is empty.

* @param file File to be verified

* @return Whether the document is valid

*/

@Override

public boolean isFileValid(String encrypt, File file) {

return TextUtils.isEmpty(encrypt) || encrypt.equalsIgnoreCase(encryptFile(file));

}

}

Finally, call the XUpdate.get().setIFileEncryptor method, settings will take effect.

3、Version update

3.1、Default version update

You can directly call the following code to complete the version update operation:

XUpdate.newBuild(getActivity())

.updateUrl(mUpdateUrl)

.update();

It should be noted that with the default version update, the JSON format returned by the request server should include the following contents:

{

"Code": 0, // 0 means the request is successful, non-0 means failure

"Msg": "", // Request error information

"UpdateStatus": 1, // 0 means no update, 1 means version update, no forced upgrade is required, and 2 represents version update and forced upgrade is required

"VersionCode": 3,

"VersionName": "1.0.2",

"ModifyContent": "1、优化api接口。\r\n2、添加使用demo演示。\r\n3、新增自定义更新服务API接口。\r\n4、优化更新提示界面。",

"DownloadUrl": "https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk",

"ApkSize": 2048

"ApkMd5": "..." // If the MD5 value of APK is not available, there is no guarantee that the APK is complete and will be downloaded again every time. The framework uses MD5 encryption by default.

}

3.2、Automatic version update

Automatic version update: auto check version + auto download APK + auto install APK (silent install).

You only need to set isAutoMode(true). However, if the device does not have root permission, it will not be able to complete automatic update (because the silent installation requires root permission).

XUpdate.newBuild(getActivity())

.updateUrl(mUpdateUrl)

.isAutoMode(true) // If you need to be completely unattended and update automatically, you need root permission【required for silent installation】

.update();

3.3、Support background update

After enabling the background update, users can enter the background update after clicking the "background update" button.

XUpdate.newBuild(getActivity())

.updateUrl(mUpdateUrl)

.supportBackgroundUpdate(true)

.update();

3.4、Force version update

If the user does not update, the program will not work normally. The server only needs to return the UpdateStatus field to 2.

Of course, if you customize the request return API, you only need to set the mIsForce field of UpdateEntity to true.

3.5、Custom version update prompt pop-up theme

By setting the update top picture, theme color, button text color, width to height ratio, etc

promptThemeColor: Set theme color

promptButtonTextColor: Set the text color of the button

promptTopResId: Set top background image Resource ID

promptWidthRatio: Set the ratio of the width of the version update prompt to the screen. The default value is -1(No constraint is required).

promptHeightRatio: Set the ratio of the height of the version update prompt to the screen. The default value is -1(No constraint is required).

XUpdate.newBuild(getActivity())

.updateUrl(mUpdateUrl)

.promptThemeColor(ResUtils.getColor(R.color.update_theme_color))

.promptButtonTextColor(Color.WHITE)

.promptTopResId(R.mipmap.bg_update_top)

.promptWidthRatio(0.7F)

.update();

3.6、Custom version update parser

The implementation of IUpdateParser interface can realize the user-defined parser.

XUpdate.newBuild(getActivity())

.updateUrl(mUpdateUrl3)

.updateParser(new CustomUpdateParser()) // Set up a custom version update parser

.update();

public class CustomUpdateParser implements IUpdateParser {

@Override

public UpdateEntity parseJson(String json) throws Exception {

CustomResult result = JsonUtil.fromJson(json, CustomResult.class);

if (result != null) {

return new UpdateEntity()

.setHasUpdate(result.hasUpdate)

.setIsIgnorable(result.isIgnorable)

.setVersionCode(result.versionCode)

.setVersionName(result.versionName)

.setUpdateContent(result.updateLog)

.setDownloadUrl(result.apkUrl)

.setSize(result.apkSize);

}

return null;

}

}

3.7、Custom version update checker + version update parser + version update prompter

By implementing the IUpdateChecker interface, the checker can be customized.

By implementing the IUpdateParser interface, the parser can be customized.

By implementing the IUpdatePrompter interface, the prompter can be customized.

XUpdate.newBuild(getActivity())

.updateUrl(mUpdateUrl3)

.updateChecker(new DefaultUpdateChecker() {

@Override

public void onBeforeCheck() {

super.onBeforeCheck();

CProgressDialogUtils.showProgressDialog(getActivity(), "查询中...");

}

@Override

public void onAfterCheck() {

super.onAfterCheck();

CProgressDialogUtils.cancelProgressDialog(getActivity());

}

})

.updateParser(new CustomUpdateParser())

.updatePrompter(new CustomUpdatePrompter(getActivity()))

.update();

public class CustomUpdatePrompter implements IUpdatePrompter {

private Context mContext;

public CustomUpdatePrompter(Context context) {

mContext = context;

}

@Override

public void showPrompt(@NonNull UpdateEntity updateEntity, @NonNull IUpdateProxy updateProxy, @NonNull PromptEntity promptEntity) {

showUpdatePrompt(updateEntity, updateProxy);

}

/**

* Show custom version update prompter

*

* @param updateEntity

* @param updateProxy

*/

private void showUpdatePrompt(final @NonNull UpdateEntity updateEntity, final @NonNull IUpdateProxy updateProxy) {

String updateInfo = UpdateUtils.getDisplayUpdateInfo(mContext, updateEntity);

new AlertDialog.Builder(mContext)

.setTitle(String.format("是否升级到%s版本?", updateEntity.getVersionName()))

.setMessage(updateInfo)

.setPositiveButton("升级", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

updateProxy.startDownload(updateEntity, new OnFileDownloadListener() {

@Override

public void onStart() {

HProgressDialogUtils.showHorizontalProgressDialog(mContext, "下载进度", false);

}

@Override

public void onProgress(float progress, long total) {

HProgressDialogUtils.setProgress(Math.round(progress * 100));

}

@Override

public boolean onCompleted(File file) {

HProgressDialogUtils.cancel();

return true;

}

@Override

public void onError(Throwable throwable) {

HProgressDialogUtils.cancel();

}

});

}

})

.setNegativeButton("暂不升级", null)

.setCancelable(false)

.create()

.show();

}

3.8、Only use the downloader function to download APK

XUpdate.newBuild(getActivity())

.apkCacheDir(PathUtils.getExtDownloadsPath()) // Set the root directory of the download cache

.build()

.download(mDownloadUrl, new OnFileDownloadListener() { // Set the download address and download listener

@Override

public void onStart() {

HProgressDialogUtils.showHorizontalProgressDialog(getContext(), "下载进度", false);

}

@Override

public void onProgress(float progress, long total) {

HProgressDialogUtils.setProgress(Math.round(progress * 100));

}

@Override

public boolean onCompleted(File file) {

HProgressDialogUtils.cancel();

ToastUtils.toast("apk下载完毕,文件路径:" + file.getPath());

return false;

}

@Override

public void onError(Throwable throwable) {

HProgressDialogUtils.cancel();

}

});

3.9、Only use the APK installed features of XUpdate

_XUpdate.startInstallApk(getContext(), FileUtils.getFileByPath(PathUtils.getFilePathByUri(getContext(), data.getData()))); // Set the path where the file is located

If your APK installation is different, you can implement your own APK installer. You only need to implement the OnInstallListener interface and use the XUpdate.setOnInstallListener set it to take effect.

Proguard

-keep class com.xuexiang.xupdate.entity.** { *; }

// Note: if you use a custom API parser for parsing, you need to add confusion to your custom API entities. Here are the custom API entity obfuscation rules configured in this demo:

-keep class com.xuexiang.xupdatedemo.entity.** { *; }

Related links

Thanks

Sponsor

Your support is the driving force of my maintenance. I will list the list of all the reward personnel at the bottom as the voucher. Please leave the notes of the support items before rewarding!

27adb3083b4bebe8d64d18356543fac7.png

Thank you for your sponsorship:

Name

Money

Platform

*天

100¥

WeChat

*航

10¥

Alipay

WeChat Subscription

More information, please scan my personal WeChat Subscription:【我的Android开源之旅】

Contact

68747470733a2f2f696d672e736869656c64732e696f2f62616467652f515147726f75702d3732303231323432352d626c75652e737667

68747470733a2f2f696d672e727275752e6e65742f696d6167652f35663764393439383434363732

框架内部支持中/英文(其他语言只需要在对应的string.xml中取相同的名字即可)内部对话框背景图片、按钮支持自定义了查看版本中的Log只需要过滤AppUpdate开头的Tag重点: 如果没有设置downloadPath则默认为getExternalCacheDir()目录,同时不会申请[存储]权限!目录编译问题效果图功能介绍DownloadManagerUpdateConfiguration使用步骤Demo下载体验版本更新记录结语编译问题因为适配了Android O的通知栏,所以依赖的v7包版本比较高appcompat-v7:26.1.0使用的gradle版本为gradle-4.1-all,所以建议使用Android Studio 3.0及以上的版本打开此项目效果图     功能介绍 支持断点下载 支持后台下载 支持自定义下载过程 支持 设备 >= Android M 动态权限的申请 支持通知栏进度条展示(或者自定义显示进度) 支持Android N 支持Android O 支持中/英文双语 支持自定内置对话框的样式 使用HttpURLConnection下载,未集成其他第三方框架更加详细的文档参阅此处《AppUpdate API文档》DownloadManager:配置文档初始化使用DownloadManager.getInstance(this)属性描述默认值是否必须设置context上下文nulltrueapkUrlapk的下载地址nulltrueapkNameapk下载好的名字nulltruedownloadPathapk下载的位置getExternalCacheDir()falseshowNewerToast是否提示用户 "当前已是最新版本"falsefalsesmallIcon通知栏的图标(资源id)-1trueconfiguration这个的额外配置nullfalseapkVersionCode更新apk的versionCode (如果设置了那么中将会进行版本判断下面的属性也就需要设置了)1falseapkVersionName更新apk的versionNamenullfalseapkDescription更新描述nullfalseapkSize新版本的安装包大小(单位M)nullfalseauthorities兼容Android N uri授权应用包名falseUpdateConfiguration:配置文档属性描述默认值notifyId通知栏消息id1011notificationChannel适配Android O的渠道通知详情查阅源码httpManager设置自己的下载过程nullbreakpointDownload是否需要支持断点下载trueenableLog是否需要日志输出trueonDownloadListener下载过程的回调nulljumpInstallPage下载完成是否自动弹出安装页面trueshowNotification是否显示通知栏进度(后台下载提示)trueforcedUpgrade是否强制升级falseonButtonClickListener按钮点击事件回调nulldialogImage对话框背景图片资源(图片规范参考demo)-1dialogButtonColor对话框按钮的颜色-1dialogButtonTextColor对话框按钮的文字颜色-1所有版本:点击查看使用步骤第一步: app/build.gradle进行依赖implementation 'com.azhon:appupdate:1.7.3'第二步:创建DownloadManager,更多用法请查看这里示例代码DownloadManager manager = DownloadManager.getInstance(this); manager.setApkName("appupdate.apk")         .setApkUrl("https://raw.githubusercontent.com/azhon/AppUpdate/master/apk/appupdate.apk")         .setSmallIcon(R.mipmap.ic_launcher)         //可设置,可不设置         .setConfiguration(configuration)         .download();第三步:兼容Android N 及以上版本,在你应用的Manifest.xml添加如下代码<--! android:authorities="${applicationId}"  这个值必须与DownloadManager中的authorities一致(不设置则为应用包名)--> <provider     android:name="android.support.v4.content.FileProvider"     android:authorities="${applicationId}"     android:exported="false"     android:grantUriPermissions="true">     <meta-data         android:name="android.support.FILE_PROVIDER_PATHS"         android:resource="@xml/file_paths_public" /> </provider>第四步:资源文件res/xml/file_paths_public.xml内容<?xml version="1.0" encoding="utf-8"?> <paths>     <external-path         name="app_update_external"         path="/" />     <external-cache-path         name="app_update_cache"         path="/" /> </paths>兼容Android O及以上版本,需要设置NotificationChannel(通知渠道);中已经写好可以前往查阅NotificationUtil.java温馨提示:升级对话框中的内容是可以上下滑动的哦!如果需要实现自己一套下载过程,只需要继承BaseHttpDownloadManager 并使用listener更新进度public class MyDownload extends BaseHttpDownloadManager {}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值