├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── layout
│ │ │ ├── activity_main.xml
│ │ │ └── dialog_version_update_download.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── duanlu
│ │ └── example
│ │ ├── VersionChecker.java
│ │ ├── OkGoDownloadStrategy.java
│ │ ├── MainActivity.java
│ │ └── SimpleDialogProvider.java
├── proguard-rules.pro
└── build.gradle
├── version_update
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ └── strings.xml
│ │ └── xml
│ │ │ └── version_update_provider_paths.xml
│ │ ├── java
│ │ └── com
│ │ │ └── duanlu
│ │ │ └── upload
│ │ │ ├── CheckCallback.java
│ │ │ ├── Checker.java
│ │ │ ├── VersionUpdateFileProvider.java
│ │ │ ├── NewVersionActionCallback.java
│ │ │ ├── DownloadStrategy.java
│ │ │ ├── DialogProvider.java
│ │ │ ├── OnDownloadStatusListener.java
│ │ │ ├── Postcard.java
│ │ │ ├── VersionUpdateUtils.java
│ │ │ └── VersionUpdate.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── encodings.xml
├── codeStyles
│ └── codeStyleConfig.xml
├── vcs.xml
├── misc.xml
├── runConfigurations.xml
└── gradle.xml
├── .gitignore
├── gradle.properties
├── config.gradle
├── gradlew.bat
├── gradlew
├── README.md
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/version_update/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':version_update'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | VersionUpdate
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/version_update/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | VersionUpdate
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FengChenSunshine/VersionUpdate/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 |
--------------------------------------------------------------------------------
/version_update/src/main/res/xml/version_update_provider_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon May 20 10:02:16 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/CheckCallback.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | /********************************
4 | * @name CheckCallback
5 | * @author 段露
6 | * @createDate 2019/05/20 13:58
7 | * @updateDate 2019/05/20 13:58
8 | * @version V1.0.0
9 | * @describe 版本更新检查回调.
10 | ********************************/
11 | public interface CheckCallback {
12 |
13 | void callback(Postcard postcard);
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/Checker.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.content.Context;
4 |
5 | /********************************
6 | * @name Checker
7 | * @author 段露
8 | * @createDate 2019/05/20 13:57
9 | * @updateDate 2019/05/20 13:57
10 | * @version V1.0.0
11 | * @describe 版本更新检查者.
12 | ********************************/
13 | public interface Checker {
14 |
15 | void check(Context context, CheckCallback callback);
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/VersionUpdateFileProvider.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.support.v4.content.FileProvider;
4 |
5 | /********************************
6 | * @name VersionUpdateFileProvider
7 | * @author 段露
8 | * @createDate 2019/05/21 10:56
9 | * @updateDate 2019/05/21 10:56
10 | * @version V1.0.0
11 | * @describe FileProvider.
12 | ********************************/
13 | public class VersionUpdateFileProvider extends FileProvider {
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/NewVersionActionCallback.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | /********************************
4 | * @name NewVersionActionCallback
5 | * @author 段露
6 | * @createDate 2019/05/20 14:58
7 | * @updateDate 2019/05/20 14:58
8 | * @version V1.0.0
9 | * @describe 新版本弹出操作回调.
10 | ********************************/
11 | public interface NewVersionActionCallback {
12 |
13 | void update();
14 |
15 | void ignore();
16 |
17 | void late();
18 |
19 | void cancel();
20 | }
21 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
16 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
15 |
16 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/DownloadStrategy.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | /********************************
6 | * @name DownloadStrategy
7 | * @author 段露
8 | * @createDate 2019/05/20 13:44
9 | * @updateDate 2019/05/20 13:44
10 | * @version V1.0.0
11 | * @describe 下载策略.
12 | ********************************/
13 | public abstract class DownloadStrategy {
14 |
15 | protected OnDownloadStatusListener mDownloadStatusListener;
16 |
17 | void download(@NonNull Postcard postcard, @NonNull OnDownloadStatusListener listener) {
18 | this.mDownloadStatusListener = listener;
19 |
20 | executeDownload(postcard);
21 | }
22 |
23 | protected abstract void executeDownload(@NonNull Postcard postcard);
24 |
25 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/version_update/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/DialogProvider.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.app.Dialog;
4 | import android.content.Context;
5 | import android.support.annotation.NonNull;
6 |
7 | /********************************
8 | * @name DialogProvider
9 | * @author 段露
10 | * @createDate 2019/05/20 14:56
11 | * @updateDate 2019/05/20 14:56
12 | * @version V1.0.0
13 | * @describe Dialog提供者.
14 | ********************************/
15 | public interface DialogProvider {
16 |
17 | /**
18 | * 新版本提醒Dialog,必须回调NewVersionActionCallback相关方法.
19 | */
20 | Dialog createNewVersionDialog(@NonNull Context context, @NonNull Postcard postcard, @NonNull NewVersionActionCallback callback);
21 |
22 | /**
23 | * 下载进度Dialog,必须实现OnDownloadStatusListener方法.
24 | */
25 | Dialog createDownloadDialog(@NonNull Context context, @NonNull Postcard postcard);
26 | }
27 |
--------------------------------------------------------------------------------
/version_update/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
16 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/config.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | ext {
3 | android = [
4 | compileSdkVersion : 28,
5 | minSdkVersion : 19,
6 | targetSdkVersion : 28,
7 | supportLibraryVersion: "28.0.0"
8 |
9 | , versionCode_dev : 1
10 | , versionName_dev : "dev0.0.1"
11 | , versionCode_beta : 1
12 | , versionName_beta : "beta0.0.1"
13 | , versionCode_release: 5
14 | , versionName_release: "v1.0.4"
15 | ]
16 | library = [
17 | junit : "junit:junit:4.12",
18 | test_runner : "com.android.support.test:runner:1.0.2",
19 | test_espresso_core : "com.android.support.test.espresso:espresso-core:3.0.2",
20 |
21 | support_appcompat : "com.android.support:appcompat-v7:28.0.0",
22 | support_annotations: "com.android.support:support-annotations:28.0.0",
23 | ]
24 | }
25 |
--------------------------------------------------------------------------------
/version_update/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | def config = rootProject.ext.android
4 | def library = rootProject.ext.library
5 |
6 | android {
7 | compileSdkVersion config.compileSdkVersion
8 | defaultConfig {
9 | minSdkVersion config.minSdkVersion
10 | targetSdkVersion config.targetSdkVersion
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 |
28 | testImplementation library.junit
29 | androidTestImplementation library.test_runner
30 | androidTestImplementation library.test_espresso_core
31 |
32 | implementation library.support_appcompat
33 | }
34 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/dialog_version_update_download.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
17 |
18 |
26 |
27 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/OnDownloadStatusListener.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.content.Intent;
4 |
5 | /********************************
6 | * @name OnDownloadStatusListener
7 | * @author 段露
8 | * @createDate 2019/05/20 10:10
9 | * @updateDate 2019/05/20 10:10
10 | * @version V1.0.0
11 | * @describe 下载状态监听器.
12 | ********************************/
13 | public interface OnDownloadStatusListener {
14 |
15 | void onStart(Postcard postcard);
16 |
17 | void onProgressChanged(long current, long total);
18 |
19 | /**
20 | * 下载完成.
21 | *
22 | * @param intent 安装intent.
23 | * @return 返回true代表已处理, false未处理交由后续程序处理.
24 | */
25 | boolean onComplete(Intent intent);
26 |
27 | /**
28 | * 下载取消.
29 | *
30 | * @return 返回true表示自己已处理后续程序不再处理;返回false时,如果是强制更新时默认推出应用.
31 | */
32 | boolean onCancel();
33 |
34 | /**
35 | * 下载失败.
36 | *
37 | * @return 返回true表示自己已处理后续程序不再处理;返回false时,如果是强制更新时默认推出应用.
38 | */
39 | boolean onError(Throwable throwable);
40 | }
41 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | def config = rootProject.ext.android
4 | def library = rootProject.ext.library
5 |
6 | android {
7 | compileSdkVersion config.compileSdkVersion
8 | defaultConfig {
9 | applicationId "com.duanlu.example"
10 | minSdkVersion config.minSdkVersion
11 | targetSdkVersion config.targetSdkVersion
12 | versionCode 1
13 | versionName "1.0"
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | implementation fileTree(dir: 'libs', include: ['*.jar'])
26 |
27 | testImplementation library.junit
28 | androidTestImplementation library.test_runner
29 | androidTestImplementation library.test_espresso_core
30 |
31 | implementation library.support_appcompat
32 |
33 | implementation project(":version_update")
34 |
35 | api 'com.lzy.net:okgo:3.0.4'
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/duanlu/example/VersionChecker.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.example;
2 |
3 | import android.content.Context;
4 | import android.os.Environment;
5 |
6 | import com.duanlu.upload.CheckCallback;
7 | import com.duanlu.upload.Checker;
8 | import com.duanlu.upload.Postcard;
9 |
10 | /********************************
11 | * @name VersionChecker
12 | * @author 段露
13 | * @createDate 2019/05/21 15:32
14 | * @updateDate 2019/05/21 15:32
15 | * @version V1.0.0
16 | * @describe 版本更新检查.
17 | ********************************/
18 | public class VersionChecker implements Checker {
19 | @Override
20 | public void check(Context context, CheckCallback callback) {
21 | String downloadUrl = "http://gdown.baidu.com/data/wisegame/f529780563bd7983/yingyongbao_7362130.apk";
22 | Postcard postcard = new Postcard.Builder(downloadUrl)
23 | .setForce(true)
24 | .setVersionDesc("有新版本啦~,是否更新?")
25 | .setVersionCode("1")
26 | .setVersionName("v1.0.3")
27 | .setSaveConfig(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AAA/", "test.apk")
28 | .build();
29 | callback.callback(postcard);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/duanlu/example/OkGoDownloadStrategy.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.example;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.duanlu.upload.DownloadStrategy;
6 | import com.duanlu.upload.Postcard;
7 | import com.lzy.okgo.OkGo;
8 | import com.lzy.okgo.callback.FileCallback;
9 | import com.lzy.okgo.model.Progress;
10 | import com.lzy.okgo.model.Response;
11 | import com.lzy.okgo.request.base.Request;
12 |
13 | import java.io.File;
14 |
15 | /********************************
16 | * @name OkGoDownloadStrategy
17 | * @author 段露
18 | * @createDate 2019/05/21 15:33
19 | * @updateDate 2019/05/21 15:33
20 | * @version V1.0.0
21 | * @describe OkGo下载策略.
22 | ********************************/
23 | public class OkGoDownloadStrategy extends DownloadStrategy {
24 | @Override
25 | protected void executeDownload(final @NonNull Postcard postcard) {
26 | OkGo.get(postcard.downloadUrl).execute(new FileCallback(postcard.saveDir, postcard.saveName) {
27 | @Override
28 | public void onStart(Request request) {
29 | super.onStart(request);
30 | mDownloadStatusListener.onStart(postcard);
31 | }
32 |
33 | @Override
34 | public void downloadProgress(Progress progress) {
35 | super.downloadProgress(progress);
36 | mDownloadStatusListener.onProgressChanged(progress.currentSize, progress.totalSize);
37 | }
38 |
39 | @Override
40 | public void onSuccess(Response response) {
41 | mDownloadStatusListener.onComplete(null);
42 | }
43 |
44 | @Override
45 | public void onError(Response response) {
46 | super.onError(response);
47 | mDownloadStatusListener.onError(response.getException());
48 | }
49 | });
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/duanlu/example/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.example;
2 |
3 | import android.Manifest;
4 | import android.content.pm.PackageManager;
5 | import android.os.Build;
6 | import android.os.Bundle;
7 | import android.support.annotation.NonNull;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.view.View;
10 |
11 | import com.duanlu.upload.VersionUpdate;
12 |
13 |
14 | public class MainActivity extends AppCompatActivity {
15 |
16 | @Override
17 | protected void onCreate(Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 | setContentView(R.layout.activity_main);
20 |
21 | findViewById(R.id.btn_update).setOnClickListener(new View.OnClickListener() {
22 |
23 | @Override
24 | public void onClick(View v) {
25 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
26 | requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
27 | } else {
28 | checkVersion();
29 | }
30 | }
31 | });
32 | }
33 |
34 | private void checkVersion() {
35 | new VersionUpdate.Builder(MainActivity.this)
36 | .debug(true)
37 | .checker(new VersionChecker())
38 | .dialogProvider(new SimpleDialogProvider())
39 | .downloadStrategy(new OkGoDownloadStrategy())
40 | .build()
41 | .check();
42 | }
43 |
44 | @Override
45 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
46 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
47 | if (1 == requestCode) {
48 | boolean isGrant = Build.VERSION.SDK_INT < Build.VERSION_CODES.M
49 | || PackageManager.PERMISSION_GRANTED == checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
50 | if (isGrant) {
51 | checkVersion();
52 | }
53 | }
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/Postcard.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | /********************************
4 | * @name Postcard
5 | * @author 段露
6 | * @createDate 2019/05/20 12:02
7 | * @updateDate 2019/05/20 12:02
8 | * @version V1.0.0
9 | * @describe 信息.
10 | ********************************/
11 | public class Postcard {
12 |
13 | public String downloadUrl;
14 | public boolean isForce;//是否强制更新.
15 | public String versionCode;//版本号.
16 | public String versionName;//版本名.
17 | public String versionDesc;//新版本描述.
18 |
19 | public String saveDir;
20 | public String saveName;
21 |
22 | private Postcard() {
23 |
24 | }
25 |
26 | public static class Builder {
27 | private String downloadUrl;
28 | private boolean isForce;//是否强制更新.
29 | private String versionCode;//版本号.
30 | private String versionName;//版本名.
31 | private String versionDesc;//新版本描述.
32 |
33 | private String saveDir;
34 | private String saveName;
35 |
36 | public Builder(String downloadUrl) {
37 | this.downloadUrl = downloadUrl;
38 | }
39 |
40 | public Builder setSaveConfig(String saveDir, String saveName) {
41 | this.saveDir = saveDir;
42 | this.saveName = saveName;
43 | return this;
44 | }
45 |
46 | public Builder setForce(boolean force) {
47 | isForce = force;
48 | return this;
49 | }
50 |
51 | public Builder setVersionCode(String versionCode) {
52 | this.versionCode = versionCode;
53 | return this;
54 | }
55 |
56 | public Builder setVersionName(String versionName) {
57 | this.versionName = versionName;
58 | return this;
59 | }
60 |
61 | public Builder setVersionDesc(String versionDesc) {
62 | this.versionDesc = versionDesc;
63 | return this;
64 | }
65 |
66 | public Postcard build() {
67 | Postcard postcard = new Postcard();
68 | postcard.downloadUrl = this.downloadUrl;
69 | postcard.isForce = this.isForce;//是否强制更新.
70 | postcard.versionCode = this.versionCode;
71 | postcard.versionName = this.versionName;
72 | postcard.versionDesc = this.versionDesc;
73 |
74 | postcard.saveDir = this.saveDir;
75 | postcard.saveName = this.saveName;
76 | return postcard;
77 | }
78 | }
79 |
80 | @Override
81 | public String toString() {
82 | return "Postcard{" +
83 | "downloadUrl='" + downloadUrl + '\'' +
84 | ", isForce=" + isForce +
85 | ", saveDir='" + saveDir + '\'' +
86 | ", saveName='" + saveName + '\'' +
87 | '}';
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/VersionUpdateUtils.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.net.Uri;
6 | import android.os.Build;
7 | import android.os.Handler;
8 | import android.support.annotation.NonNull;
9 | import android.text.TextUtils;
10 | import android.webkit.MimeTypeMap;
11 |
12 | import java.io.File;
13 | import java.io.IOException;
14 |
15 | /********************************
16 | * @name VersionUpdateUtils
17 | * @author 段露
18 | * @createDate 2019/05/20 10:15
19 | * @updateDate 2019/05/20 10:15
20 | * @version V1.0.0
21 | * @describe 版本更新工具类.
22 | ********************************/
23 | class VersionUpdateUtils {
24 |
25 | static Intent getInstallAppIntent(@NonNull Context context, @NonNull File file, String authority) {
26 | Intent intent = new Intent(Intent.ACTION_VIEW);
27 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
28 | //适配API23 Android6.0以上获取文件Uri.
29 | Uri contentUri = getUriFromFile(context, file, authority);
30 | String type;
31 | //API23 Android6.0以上获取type.
32 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
33 | type = "application/vnd.android.package-archive";
34 | } else {
35 | type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtension(file));
36 | }
37 | //API24 Android7.0以上需要添加权限.
38 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
39 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
40 | }
41 | intent.setDataAndType(contentUri, type);
42 | return intent;
43 | }
44 |
45 | private static Uri getUriFromFile(Context context, File file, String authority) {
46 | Uri uri = null;
47 | if (null != file) {
48 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
49 | //第二个参数为在Manifest定义的provider的authorities属性
50 | uri = VersionUpdateFileProvider.getUriForFile(context, authority, file);
51 | } else {
52 | uri = Uri.fromFile(file);
53 | }
54 | }
55 | return uri;
56 | }
57 |
58 | private static String getFileExtension(File file) {
59 | if (file == null) return null;
60 | return getFileExtension(file.getPath());
61 | }
62 |
63 | private static String getFileExtension(String filePath) {
64 | if (TextUtils.isEmpty(filePath.trim())) return filePath;
65 | int lastPoi = filePath.lastIndexOf('.');
66 | int lastSep = filePath.lastIndexOf(File.separator);
67 | if (lastPoi == -1 || lastSep >= lastPoi) return "";
68 | return filePath.substring(lastPoi + 1);
69 | }
70 |
71 | static boolean isFileExists(File file) {
72 | return file != null && file.exists();
73 | }
74 |
75 | static boolean createFileByDeleteOldFile(File file) {
76 | if (file == null) return false;
77 | // 文件存在并且删除失败返回false
78 | if (file.exists() && file.isFile() && !file.delete()) return false;
79 | // 创建目录失败返回false
80 | if (!createOrExistsDir(file.getParentFile())) return false;
81 | try {
82 | return file.createNewFile();
83 | } catch (IOException e) {
84 | e.printStackTrace();
85 | return false;
86 | }
87 | }
88 |
89 | private static boolean createOrExistsFile(File file) {
90 | if (file == null) return false;
91 | // 如果存在,是文件则返回true,是目录则返回false
92 | if (file.exists()) return file.isFile();
93 | if (!createOrExistsDir(file.getParentFile())) return false;
94 | try {
95 | return file.createNewFile();
96 | } catch (IOException e) {
97 | e.printStackTrace();
98 | return false;
99 | }
100 | }
101 |
102 | private static boolean createOrExistsDir(File file) {
103 | // 如果存在,是目录则返回true,是文件则返回false,不存在则返回是否创建成功
104 | return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
105 | }
106 |
107 | static void killApplication(int delayMillis) {
108 | new Handler().postDelayed(new Runnable() {
109 |
110 | @Override
111 | public void run() {
112 | AppExit();
113 | }
114 | }, delayMillis);
115 | }
116 |
117 | private static void AppExit() {
118 | try {
119 | android.os.Process.killProcess(android.os.Process.myPid());
120 | System.exit(1);
121 | } catch (Exception e) {
122 | e.printStackTrace();
123 | }
124 | }
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/app/src/main/java/com/duanlu/example/SimpleDialogProvider.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.example;
2 |
3 | import android.app.AlertDialog;
4 | import android.app.Dialog;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.content.Intent;
8 | import android.os.Build;
9 | import android.support.annotation.NonNull;
10 | import android.view.LayoutInflater;
11 | import android.view.View;
12 | import android.widget.LinearLayout;
13 | import android.widget.ProgressBar;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import com.duanlu.upload.DialogProvider;
18 | import com.duanlu.upload.NewVersionActionCallback;
19 | import com.duanlu.upload.OnDownloadStatusListener;
20 | import com.duanlu.upload.Postcard;
21 |
22 | import java.util.Locale;
23 |
24 | /********************************
25 | * @name SimpleDialogProvider
26 | * @author 段露
27 | * @createDate 2019/05/20 17:06
28 | * @updateDate 2019/05/20 17:06
29 | * @version V1.0.0
30 | * @describe 一个简单的DialogProvider.
31 | ********************************/
32 | public class SimpleDialogProvider implements DialogProvider {
33 |
34 | @Override
35 | public Dialog createNewVersionDialog(@NonNull Context context, @NonNull Postcard postcard, final @NonNull NewVersionActionCallback callback) {
36 | DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
37 | @Override
38 | public void onClick(DialogInterface dialog, int which) {
39 | switch (which) {
40 | case DialogInterface.BUTTON_NEGATIVE:
41 | callback.cancel();
42 | break;
43 | case DialogInterface.BUTTON_NEUTRAL:
44 | callback.late();
45 | break;
46 | case DialogInterface.BUTTON_POSITIVE:
47 | callback.update();
48 | break;
49 | }
50 | }
51 | };
52 |
53 | AlertDialog.Builder builder = new AlertDialog.Builder(context)
54 | .setTitle("版本更新")
55 | .setMessage(postcard.versionDesc)
56 | .setPositiveButton("更新", listener)
57 | .setCancelable(false);
58 | if (!postcard.isForce) {
59 | builder.setNegativeButton("取消", listener)
60 | .setNeutralButton("稍后提醒", listener);
61 | }
62 |
63 | return builder.create();
64 | }
65 |
66 | @Override
67 | public Dialog createDownloadDialog(@NonNull Context context, @NonNull Postcard postcard) {
68 | return new DownloadDialog(context);
69 | }
70 |
71 | private class DownloadDialog extends AlertDialog implements OnDownloadStatusListener {
72 | ProgressBar progressBar;
73 | TextView tvPercent;
74 |
75 | protected DownloadDialog(Context context) {
76 | super(context);
77 |
78 | setCancelable(false);
79 |
80 | setTitle("下载进度");
81 |
82 | View container = LayoutInflater.from(context).inflate(R.layout.dialog_version_update_download, null);
83 | setView(container);
84 |
85 | progressBar = container.findViewById(R.id.progress_bar);
86 | tvPercent = container.findViewById(R.id.tv_percent);
87 | }
88 |
89 | @Override
90 | public void onStart(Postcard postcard) {
91 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
92 | progressBar.setProgress(0, true);
93 | } else {
94 | progressBar.setProgress(0);
95 | }
96 | tvPercent.setText("0.0%");
97 | }
98 |
99 | @Override
100 | public void onProgressChanged(long current, long total) {
101 | double percent = ((double) current / (double) total);
102 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
103 | progressBar.setProgress((int) (percent * 100), true);
104 | } else {
105 | progressBar.setProgress((int) (percent * 100));
106 | }
107 | tvPercent.setText(String.format(Locale.getDefault(), "%.1f", percent * 100) + "%");
108 | }
109 |
110 | @Override
111 | public boolean onComplete(Intent intent) {
112 | return false;
113 | }
114 |
115 | @Override
116 | public boolean onCancel() {
117 | return false;
118 | }
119 |
120 | @Override
121 | public boolean onError(Throwable throwable) {
122 | Toast.makeText(getContext(), throwable.getMessage(), Toast.LENGTH_LONG).show();
123 | return false;
124 | }
125 | }
126 |
127 | }
128 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # VersionUpdate
2 | ### 提供一个应用版本更新功能的库](https://jitpack.io/#FengChenSunshine/VersionUpdate)
3 | [](https://github.com/FengChenSunshine/LibraryModel/blob/master/LICENSE)
4 |
5 | ### 优势:
6 | 1.完全解耦:从版本检查到下载安装每一步都完全解耦,通过接口实现可以自由配置;
7 |
8 | 2.兼容性强:使用该库无需关心各版本(6.0、7.0、8.0、9.0等)差异造成的适配问题,其内部已经兼容了各版本差异;
9 |
10 | 3.使用简单:链式调用,逻辑清晰,使用简单。
11 |
12 | ### 使用方法:
13 | private void checkVersion() {
14 | new VersionUpdate.Builder(MainActivity.this)
15 | .debug(true)
16 | .checker(new VersionChecker())
17 | .dialogProvider(new SimpleDialogProvider())
18 | .downloadStrategy(new OkGoDownloadStrategy())
19 | .build()
20 | .check();
21 | }
22 | 1.其中debug()方法传入true时可以调试打印详细日志信息;
23 |
24 | 2.checker()方法传入一个实现了Checker接口的对象,该方法内一般调取接口实现自己的版本检查逻辑,并构造一个Postcard对象返回;
25 |
26 | 3.dialogProvider()方法传入一个实现了DialogProvider接口的对象,该对象提供了创建新版本提醒Dialog和下载进度Dialog,其中下载进度Dialog必须实现OnDownloadStatusListener接口;
27 |
28 | 4.downloadStrategy()方法传入一个继承DownloadStrategy的对象,该对象实现了具体的下载逻辑,并通过其内部mDownloadStatusListener对象回调给VersionUpdate库。使用时可以自行实现自己的下载策略,比如基于OkGo、OkHttp、DownloadManager等;
29 |
30 | 5.最后通过build()方法构建VersionUpdate对象并调用其check()方法开启检查。
31 |
32 | 6.注意:由于该库的重点不在于权限申请,所以针对Android6.0以上需要自行判断读写权限是否赋予!!!
33 |
34 | ## 简单使用举例:
35 | ### step 1.
36 | private void checkVersion() {
37 | new VersionUpdate.Builder(MainActivity.this)
38 | .debug(true)
39 | .checker(new VersionChecker())
40 | .dialogProvider(new SimpleDialogProvider())
41 | .downloadStrategy(new OkGoDownloadStrategy())
42 | .build()
43 | .check();
44 | }
45 | ### Checker举例.
46 | public class VersionChecker implements Checker {
47 | @Override
48 | public void check(Context context, CheckCallback callback) {
49 | String downloadUrl = "http://gdown.baidu.com/data/wisegame/f529780563bd7983/yingyongbao_7362130.apk";
50 | Postcard postcard = new Postcard.Builder(downloadUrl)
51 | .setForce(true)
52 | .setVersionDesc("有新版本啦~,是否更新?")
53 | .setVersionCode("1")
54 | .setVersionName("v1.0.3")
55 | .setSaveConfig(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AAA/", "test.apk")
56 | .build();
57 | callback.callback(postcard);
58 | }
59 | }
60 |
61 | ### DialogProvider举例.
62 | public class SimpleDialogProvider implements DialogProvider {
63 |
64 | @Override
65 | public Dialog createNewVersionDialog(@NonNull Context context, @NonNull Postcard postcard, final @NonNull NewVersionActionCallback callback) {
66 | DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
67 | @Override
68 | public void onClick(DialogInterface dialog, int which) {
69 | switch (which) {
70 | case DialogInterface.BUTTON_NEGATIVE:
71 | callback.cancel();
72 | break;
73 | case DialogInterface.BUTTON_NEUTRAL:
74 | callback.late();
75 | break;
76 | case DialogInterface.BUTTON_POSITIVE:
77 | callback.update();
78 | break;
79 | }
80 | }
81 | };
82 |
83 | AlertDialog.Builder builder = new AlertDialog.Builder(context)
84 | .setTitle("版本更新")
85 | .setMessage(postcard.versionDesc)
86 | .setPositiveButton("更新", listener)
87 | .setCancelable(false);
88 | if (!postcard.isForce) {
89 | builder.setNegativeButton("取消", listener)
90 | .setNeutralButton("稍后提醒", listener);
91 | }
92 |
93 | return builder.create();
94 | }
95 |
96 | @Override
97 | public Dialog createDownloadDialog(@NonNull Context context, @NonNull Postcard postcard) {
98 | return new DownloadDialog(context);
99 | }
100 |
101 | private class DownloadDialog extends AlertDialog implements OnDownloadStatusListener {
102 | ProgressBar progressBar;
103 | TextView tvPercent;
104 |
105 | protected DownloadDialog(Context context) {
106 | super(context);
107 |
108 | setTitle("下载进度");
109 |
110 | setCancelable(false);
111 |
112 | setTitle("下载进度");
113 |
114 | View container = LayoutInflater.from(context).inflate(R.layout.dialog_version_update_download, null);
115 | setView(container);
116 |
117 | progressBar = container.findViewById(R.id.progress_bar);
118 | tvPercent = container.findViewById(R.id.tv_percent);
119 | }
120 |
121 | @Override
122 | public void onStart(Postcard postcard) {
123 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
124 | progressBar.setProgress(0, true);
125 | } else {
126 | progressBar.setProgress(0);
127 | }
128 | tvPercent.setText("0.0%");
129 | }
130 |
131 | @Override
132 | public void onProgressChanged(long current, long total) {
133 | double percent = ((double) current / (double) total);
134 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
135 | progressBar.setProgress((int) (percent * 100), true);
136 | } else {
137 | progressBar.setProgress((int) (percent * 100));
138 | }
139 | tvPercent.setText(String.format(Locale.getDefault(), "%.1f", percent * 100) + "%");
140 | }
141 |
142 | @Override
143 | public boolean onComplete(Intent intent) {
144 | return false;
145 | }
146 |
147 | @Override
148 | public boolean onCancel() {
149 | return false;
150 | }
151 |
152 | @Override
153 | public boolean onError(Throwable throwable) {
154 | Toast.makeText(getContext(), throwable.getMessage(), Toast.LENGTH_LONG).show();
155 | return false;
156 | }
157 | }
158 |
159 | }
160 |
161 | ### DownloadStrategy举例.
162 | public class OkGoDownloadStrategy extends DownloadStrategy {
163 | @Override
164 | protected void executeDownload(final @NonNull Postcard postcard) {
165 | OkGo.get(postcard.downloadUrl).execute(new FileCallback(postcard.saveDir, postcard.saveName) {
166 | @Override
167 | public void onStart(Request request) {
168 | super.onStart(request);
169 | mDownloadStatusListener.onStart(postcard);
170 | }
171 |
172 | @Override
173 | public void downloadProgress(Progress progress) {
174 | super.downloadProgress(progress);
175 | mDownloadStatusListener.onProgressChanged(progress.currentSize, progress.totalSize);
176 | }
177 |
178 | @Override
179 | public void onSuccess(Response response) {
180 | mDownloadStatusListener.onComplete(null);
181 | }
182 |
183 | @Override
184 | public void onError(Response response) {
185 | super.onError(response);
186 | mDownloadStatusListener.onError(response.getException());
187 | }
188 | });
189 | }
190 | }
191 |
192 |
193 | ## 怎样使用?
194 | Step 1. Add the JitPack repository to your build file,Add it in your root build.gradle at the end of repositories:
195 |
196 | allprojects {
197 | repositories {
198 | ...
199 | maven { url 'https://jitpack.io' }
200 | }
201 | }
202 | Step 2. Add the dependency
203 |
204 | dependencies {
205 | implementation 'com.github.FengChenSunshine:VersionUpdate:v1.0.4'
206 | }
207 |
208 | ## 8.版本说明
209 |
210 | ### v1.0.4
211 | 1.修复某些机型下载成功安装失败,或者安装成功之后没有显示系统安装成功结果界面,或者点击打开时回到桌面的Bug。
212 | 2.备注:安装时使用的一定要是addFlags方法而不是setFlags方法,这个很重要,很重要,很重要。
213 |
214 | ### v1.0.3
215 | 1.Postcard对象里增加版本号、版本名和版本描述信息。
216 | 2.更新Demo。
217 |
218 | ### v1.0.2
219 | 1.创建Dialog接口参数里增加Postcard对象,这样方便在创建Dialog时根据不同条件创建不同内容的Dialog。
220 |
221 | ### v1.0.1
222 | 1.修改使用该库的2个APP不能同时安装的问题。
223 |
224 | ## 9.链接
225 | 1.[](https://github.com/FengChenSunshine/UiStatus)是我的另一个开源库:一个简单且强大的Ui状态视图控制库!喜欢的可以看看,欢迎start!!!
226 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/version_update/src/main/java/com/duanlu/upload/VersionUpdate.java:
--------------------------------------------------------------------------------
1 | package com.duanlu.upload;
2 |
3 | import android.app.Dialog;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.os.Handler;
8 | import android.os.Message;
9 | import android.support.annotation.NonNull;
10 | import android.text.TextUtils;
11 | import android.util.Log;
12 |
13 | import java.io.File;
14 | import java.io.FileNotFoundException;
15 | import java.lang.ref.WeakReference;
16 |
17 | /********************************
18 | * @name VersionUpdate
19 | * @author 段露
20 | * @createDate 2019/05/20 13:51
21 | * @updateDate 2019/05/20 13:51
22 | * @version V1.0.0
23 | * @describe 版本更新管理者.
24 | ********************************/
25 | public class VersionUpdate implements CheckCallback, NewVersionActionCallback, OnDownloadStatusListener {
26 |
27 | private static final String TAG = "VersionUpdate";
28 | private static final String AUTHORITY = ".version_update";
29 | private boolean isDebug;
30 | private Context mContext;
31 | private Checker mChecker;
32 |
33 | private DialogProvider mDialogProvider;
34 | private Dialog mNewVersionDialog;
35 | private Dialog mDownloadDialog;
36 |
37 | private DownloadStrategy mDownloadStrategy;
38 |
39 | private Postcard mPostcard;
40 |
41 | private OnDownloadStatusListener mDownloadStatusListener;
42 |
43 | private Handler mHandler;
44 |
45 | private VersionUpdate(Context context) {
46 | this.mContext = context;
47 | }
48 |
49 | public void check() {
50 | if (null == mChecker) {
51 | throw new RuntimeException("Please set Checker!!!");
52 | }
53 | mChecker.check(mContext, this);
54 | }
55 |
56 | @Override
57 | public void callback(Postcard postcard) {
58 | if (null != postcard && !TextUtils.isEmpty(postcard.downloadUrl)) {
59 |
60 | this.mPostcard = postcard;
61 |
62 | File file = new File(mPostcard.saveDir, mPostcard.saveName);
63 | if (!VersionUpdateUtils.createFileByDeleteOldFile(file)) {
64 | if (isDebug) {
65 | Log.i(TAG, "版本更新——创建文件失败");
66 | }
67 | onError(new FileNotFoundException("创建文件失败"));
68 | }
69 |
70 | if (isDebug) {
71 | Log.i(TAG, String.format("版本更新——提醒更新[%s]", mPostcard.toString()));
72 | }
73 |
74 | ensureNewVersionDialog();
75 |
76 | showDialog(mNewVersionDialog);
77 |
78 | } else {
79 | if (isDebug) {
80 | Log.i(TAG, "版本更新——已经是最新版本了~");
81 | }
82 | //已经是最新版本了.
83 | }
84 | }
85 |
86 | @Override
87 | public void update() {
88 | if (isDebug) {
89 | Log.i(TAG, "版本更新——准备下载APK文件");
90 | }
91 |
92 | dismissDialog(mNewVersionDialog);
93 |
94 | ensureDownloadDialog();
95 |
96 | if (null == mHandler) {
97 | mHandler = new DownloadHandler(this);
98 | } else {
99 | onCancel();
100 | }
101 |
102 | mDownloadStrategy.download(mPostcard, this);
103 | }
104 |
105 | @Override
106 | public void ignore() {
107 | dismissDialog(mDownloadDialog);
108 | }
109 |
110 | @Override
111 | public void late() {
112 | dismissDialog(mDownloadDialog);
113 | }
114 |
115 | @Override
116 | public void cancel() {
117 | dismissDialog(mDownloadDialog);
118 | }
119 |
120 | private void ensureNewVersionDialog() {
121 | if (null == mNewVersionDialog && null != mDialogProvider) {
122 | mNewVersionDialog = mDialogProvider.createNewVersionDialog(mContext, mPostcard, this);
123 | }
124 | if (null == mNewVersionDialog) {
125 | throw new RuntimeException("NewVersionDialog is Null!");
126 | }
127 | }
128 |
129 | private void ensureDownloadDialog() {
130 | if (null == mDownloadDialog && null != mDialogProvider) {
131 | mDownloadDialog = mDialogProvider.createDownloadDialog(mContext, mPostcard);
132 | }
133 |
134 | if (!(mDownloadDialog instanceof OnDownloadStatusListener)) {
135 | throw new RuntimeException("DownloadDialog must implements OnDownloadStatusListener!");
136 | }
137 | mDownloadStatusListener = (OnDownloadStatusListener) mDownloadDialog;
138 | }
139 |
140 | @Override
141 | public void onStart(Postcard postcard) {
142 | if (isDebug) {
143 | Log.i(TAG, "开始下载APK文件");
144 | }
145 | mHandler.sendEmptyMessage(WHAT_START);
146 | }
147 |
148 | @Override
149 | public void onProgressChanged(long current, long total) {
150 | if (isDebug) {
151 | Log.i(TAG, String.format("APK文件下载进度:current=%d,total=%d", current, total));
152 | }
153 | Message message = Message.obtain(mHandler, WHAT_PROGRESS_CHANGED);
154 | Bundle bundle = new Bundle();
155 | bundle.putLong("current", current);
156 | bundle.putLong("total", total);
157 | message.setData(bundle);
158 | message.sendToTarget();
159 | }
160 |
161 | @Override
162 | public boolean onComplete(@NonNull Intent intent) {
163 | if (isDebug) {
164 | Log.i(TAG, "APK文件下载完成");
165 | }
166 |
167 | mHandler.sendEmptyMessage(WHAT_COMPLETE);
168 | return true;
169 | }
170 |
171 | @Override
172 | public boolean onCancel() {
173 | if (isDebug) {
174 | Log.i(TAG, "APK文件下载取消");
175 | }
176 | mHandler.sendEmptyMessage(WHAT_CANCEL);
177 | return true;
178 | }
179 |
180 | @Override
181 | public boolean onError(Throwable throwable) {
182 | if (isDebug) {
183 | Log.i(TAG, String.format("APK文件下载失败:%s", throwable.getMessage()));
184 | }
185 |
186 | Message message = Message.obtain(mHandler, WHAT_ERROR);
187 | Bundle bundle = new Bundle();
188 | bundle.putSerializable("throwable", throwable);
189 | message.setData(bundle);
190 | message.sendToTarget();
191 |
192 | return true;
193 | }
194 |
195 | private static final int WHAT_START = 1;
196 | private static final int WHAT_PROGRESS_CHANGED = 2;
197 | private static final int WHAT_COMPLETE = 3;
198 | private static final int WHAT_CANCEL = 4;
199 | private static final int WHAT_ERROR = 5;
200 |
201 | private static class DownloadHandler extends Handler {
202 |
203 | private WeakReference mVersionUpdate;
204 |
205 | private DownloadHandler(VersionUpdate versionUpdate) {
206 | mVersionUpdate = new WeakReference<>(versionUpdate);
207 | }
208 |
209 | @Override
210 | public void dispatchMessage(Message msg) {
211 | super.dispatchMessage(msg);
212 | VersionUpdate versionUpdate = mVersionUpdate.get();
213 | boolean result;
214 | switch (msg.what) {
215 | case WHAT_START://开始下载.
216 | versionUpdate.showDialog(versionUpdate.mDownloadDialog);
217 |
218 | versionUpdate.mDownloadStatusListener.onStart(versionUpdate.mPostcard);
219 | break;
220 | case WHAT_PROGRESS_CHANGED://下载进度改变.
221 | Bundle bundle = msg.getData();
222 | versionUpdate.mDownloadStatusListener.onProgressChanged(
223 | bundle.getLong("current"),
224 | bundle.getLong("total"));
225 | break;
226 | case WHAT_COMPLETE://下载完成.
227 | Context context = versionUpdate.mDownloadDialog.getContext();
228 | File apkFile = new File(versionUpdate.mPostcard.saveDir, versionUpdate.mPostcard.saveName);
229 | if (!VersionUpdateUtils.isFileExists(apkFile)) {
230 | if (versionUpdate.isDebug) {
231 | Log.i(TAG, "下载APK文件未找到");
232 | }
233 | versionUpdate.onError(new FileNotFoundException("下载APK文件未找到"));
234 | return;
235 | }
236 | Intent intent = VersionUpdateUtils.getInstallAppIntent(context, apkFile, context.getPackageName() + AUTHORITY);
237 | result = versionUpdate.mDownloadStatusListener.onComplete(intent);
238 | if (!result) {
239 | if (versionUpdate.isDebug) {
240 | Log.i(TAG, "安装APK文件:" + apkFile.getAbsolutePath());
241 | }
242 | context.startActivity(intent);
243 | }
244 | versionUpdate.dismissDialog(versionUpdate.mDownloadDialog);
245 | break;
246 | case WHAT_CANCEL://下载取消.
247 | if (versionUpdate.isDebug) {
248 | Log.i(TAG, "下载取消");
249 | }
250 | result = versionUpdate.mDownloadStatusListener.onCancel();
251 | versionUpdate.dismissDialog(versionUpdate.mDownloadDialog);
252 | if (!result && versionUpdate.mPostcard.isForce) {
253 | if (versionUpdate.isDebug) {
254 | Log.i(TAG, "下载取消,当前为强制更新,2s后将自动退出应用");
255 | }
256 | VersionUpdateUtils.killApplication(2000);
257 | }
258 | break;
259 | case WHAT_ERROR://下载失败.
260 | if (versionUpdate.isDebug) {
261 | Log.i(TAG, "下载失败");
262 | }
263 | Bundle throwableBundle = msg.getData();
264 | result = versionUpdate.mDownloadStatusListener.onError((Throwable) throwableBundle.getSerializable("throwable"));
265 | versionUpdate.dismissDialog(versionUpdate.mDownloadDialog);
266 | if (!result && versionUpdate.mPostcard.isForce) {
267 | if (versionUpdate.isDebug) {
268 | Log.i(TAG, "下载失败,当前为强制更新,2s后将自动退出应用");
269 | }
270 | VersionUpdateUtils.killApplication(2000);
271 | }
272 | break;
273 | }
274 | }
275 | }
276 |
277 | public static class Builder {
278 | private boolean isDebug;
279 | private Context context;
280 | private Checker checker;
281 |
282 | private DialogProvider dialogProvider;
283 | private DownloadStrategy downloadStrategy;
284 |
285 | public Builder(Context context) {
286 | this.context = context;
287 | }
288 |
289 | public Builder debug(boolean debug) {
290 | this.isDebug = debug;
291 | return this;
292 | }
293 |
294 | public Builder checker(Checker checker) {
295 | this.checker = checker;
296 | return this;
297 | }
298 |
299 | public Builder dialogProvider(DialogProvider provider) {
300 | this.dialogProvider = provider;
301 | return this;
302 | }
303 |
304 | public Builder downloadStrategy(DownloadStrategy strategy) {
305 | this.downloadStrategy = strategy;
306 | return this;
307 | }
308 |
309 | public VersionUpdate build() {
310 | VersionUpdate versionUpdate = new VersionUpdate(context);
311 | versionUpdate.isDebug = isDebug;
312 | versionUpdate.mChecker = checker;
313 | versionUpdate.mDialogProvider = dialogProvider;
314 | versionUpdate.mDownloadStrategy = downloadStrategy;
315 | return versionUpdate;
316 | }
317 |
318 | public void check() {
319 | build().check();
320 | }
321 | }
322 |
323 | private void showDialog(Dialog dialog) {
324 | if (null != dialog && !dialog.isShowing()) {
325 | dialog.show();
326 | }
327 | }
328 |
329 | private void dismissDialog(Dialog dialog) {
330 | if (null != dialog && dialog.isShowing()) {
331 | dialog.dismiss();
332 | }
333 | }
334 |
335 | }
336 |
--------------------------------------------------------------------------------