├── update
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── xml
│ │ │ └── file_paths.xml
│ │ ├── values
│ │ │ ├── colors.xml
│ │ │ ├── style.xml
│ │ │ └── strings.xml
│ │ └── layout
│ │ │ └── update_dialog_layout.xml
│ │ ├── java
│ │ └── pers
│ │ │ └── loren
│ │ │ └── appupdate
│ │ │ ├── interfaces
│ │ │ ├── CheckUpdateListener.java
│ │ │ ├── CheckUpdateBean.java
│ │ │ └── UpdateDownloadListener.java
│ │ │ ├── providers
│ │ │ ├── LorenProvider.java
│ │ │ └── ResolveConflictProvider.java
│ │ │ ├── utils
│ │ │ ├── AppUpdateUtils.java
│ │ │ └── StorageUtils.java
│ │ │ ├── UpdateDialog.java
│ │ │ ├── view
│ │ │ └── DownloadProcessView.java
│ │ │ ├── AppUpdateManager.java
│ │ │ └── DownloadService.java
│ │ └── AndroidManifest.xml
├── build.gradle
└── proguard-rules.pro
├── settings.gradle
├── images
├── image01.png
├── image02.png
└── image03.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
├── README-1.x.md
└── README.md
/update/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':update'
2 |
--------------------------------------------------------------------------------
/images/image01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Loren1994/AndroidUpdate/HEAD/images/image01.png
--------------------------------------------------------------------------------
/images/image02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Loren1994/AndroidUpdate/HEAD/images/image02.png
--------------------------------------------------------------------------------
/images/image03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Loren1994/AndroidUpdate/HEAD/images/image03.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Loren1994/AndroidUpdate/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | build
7 | /captures
8 | app
9 | testlibrary
10 | update/libs/
11 | update/src/main/res/drawable/
12 |
--------------------------------------------------------------------------------
/update/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/interfaces/CheckUpdateListener.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.interfaces;
2 |
3 | /**
4 | * Copyright © 2018/12/28 by loren
5 | */
6 | public interface CheckUpdateListener {
7 | void checkUpdate();
8 | }
9 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/interfaces/CheckUpdateBean.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.interfaces;
2 |
3 | /**
4 | * Copyright © 2018/12/28 by loren
5 | * 更新feature
6 | */
7 | public interface CheckUpdateBean {
8 | boolean isUpdate();
9 | }
10 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jan 24 11:29:51 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
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/providers/LorenProvider.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.providers;
2 |
3 | import android.support.v4.content.FileProvider;
4 |
5 | /**
6 | * Copyright © 24/10/2017 by loren
7 | */
8 |
9 | public class LorenProvider extends FileProvider {
10 | }
11 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/providers/ResolveConflictProvider.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.providers;
2 |
3 | import android.support.v4.content.FileProvider;
4 |
5 | /**
6 | * Copyright © 24/10/2017 by loren
7 | */
8 |
9 | public class ResolveConflictProvider extends FileProvider {
10 | }
11 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/interfaces/UpdateDownloadListener.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.interfaces;
2 |
3 | /**
4 | * Copyright © 2018/12/29 by loren
5 | */
6 | public interface UpdateDownloadListener {
7 | void onDownloading(int process);
8 |
9 | void onDownloadSuccess();
10 |
11 | void onDownloadFail(String reason);
12 | }
13 |
--------------------------------------------------------------------------------
/update/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #ececec
4 |
5 | #38abfc
6 | #333333
7 | #f8f8f8
8 | #bbbbbb
9 | #00000000
10 |
11 |
--------------------------------------------------------------------------------
/update/src/main/res/values/style.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/update/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 |
4 | group='com.github.Loren1994'
5 |
6 | android {
7 | compileSdkVersion 27
8 | buildToolsVersion '28.0.3'
9 |
10 | defaultConfig {
11 | minSdkVersion 16
12 | targetSdkVersion 27
13 | versionCode 20190114
14 | versionName "2.0.1"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | implementation 'com.android.support:appcompat-v7:27.1.1'
26 | }
27 |
--------------------------------------------------------------------------------
/update/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 发现新版本
3 |
4 | 发现新版本,点击进行升级
5 | 发现新版本,点击进行升级
6 |
7 | 立即下载
8 | 以后再说
9 |
10 | 已经是最新版本
11 |
12 | 正在下载:%1$d%%
13 |
14 | 正在检查版本
15 |
16 |
17 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/update/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/loren/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/utils/AppUpdateUtils.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.utils;
2 |
3 | import android.content.Context;
4 | import android.content.pm.PackageManager;
5 |
6 | @SuppressWarnings("unused")
7 | public class AppUpdateUtils {
8 |
9 |
10 | private AppUpdateUtils() {
11 | }
12 |
13 | public static int getVersionCode(Context context) {
14 | if (context != null) {
15 | try {
16 | return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
17 | } catch (PackageManager.NameNotFoundException ignored) {
18 | }
19 | }
20 | return 0;
21 | }
22 |
23 | public static String getVersionName(Context context) {
24 | if (context != null) {
25 | try {
26 | return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
27 | } catch (PackageManager.NameNotFoundException ignored) {
28 | }
29 | }
30 | return "";
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/update/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
17 |
20 |
21 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/utils/StorageUtils.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.utils;
2 |
3 | import android.content.Context;
4 | import android.content.pm.PackageManager;
5 | import android.os.Environment;
6 | import android.util.Log;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 |
11 | import static android.os.Environment.MEDIA_MOUNTED;
12 |
13 | @SuppressWarnings("unused")
14 | final class StorageUtils {
15 |
16 | private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";
17 |
18 | private StorageUtils() {
19 | }
20 |
21 | public static File getCacheDirectory(Context context) {
22 | File appCacheDir = null;
23 | if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
24 | appCacheDir = getExternalCacheDir(context);
25 | }
26 | if (appCacheDir == null) {
27 | appCacheDir = context.getCacheDir();
28 | }
29 | return appCacheDir;
30 | }
31 |
32 |
33 | private static File getExternalCacheDir(Context context) {
34 | File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
35 | File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
36 | if (!appCacheDir.exists()) {
37 | if (!appCacheDir.mkdirs()) {
38 | Log.w("Update", "Unable to create external cache directory");
39 | return null;
40 | }
41 | try {
42 | Log.i("Update",
43 | "file create success:" + new File(appCacheDir, ".nomedia").createNewFile());
44 | } catch (IOException e) {
45 | Log.i("Update",
46 | "Can't create \".nomedia\" file in application external cache directory");
47 | }
48 | }
49 | return appCacheDir;
50 | }
51 |
52 | private static boolean hasExternalStoragePermission(Context context) {
53 | int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
54 | return perm == PackageManager.PERMISSION_GRANTED;
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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
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 Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/UpdateDialog.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate;
2 |
3 | import android.app.AlertDialog;
4 | import android.content.Context;
5 | import android.graphics.Color;
6 | import android.view.View;
7 | import android.widget.TextView;
8 |
9 | import pers.loren.appupdate.view.DownloadProcessView;
10 |
11 | /**
12 | * Created by loren on 2017/3/16.
13 | */
14 | class UpdateDialog {
15 |
16 | private static AlertDialog forceUpdateDialog = null;
17 |
18 | static void showUpdateDialog(Context mContext, String content, final OnConfirmListener listener) {
19 | final AlertDialog updateDialog = new AlertDialog.Builder(mContext, R.style.ProcessDialog)
20 | .setCancelable(false).create();
21 | View view = View.inflate(mContext, R.layout.update_dialog_layout, null);
22 | updateDialog.show();
23 | updateDialog.setContentView(view);
24 | updateDialog.findViewById(R.id.process_view).setVisibility(View.GONE);
25 | ((TextView) updateDialog.findViewById(R.id.content_tv)).setText(content);
26 | updateDialog.findViewById(R.id.confirm_tv).setOnClickListener(new View.OnClickListener() {
27 | @Override
28 | public void onClick(View v) {
29 | updateDialog.dismiss();
30 | listener.onConfirm();
31 | }
32 | });
33 | updateDialog.findViewById(R.id.cancel_tv).setOnClickListener(new View.OnClickListener() {
34 | @Override
35 | public void onClick(View v) {
36 | updateDialog.dismiss();
37 | }
38 | });
39 | }
40 |
41 | static void showUpdateForceDialog(Context mContext, String content, final OnConfirmListener listener) {
42 | forceUpdateDialog = new AlertDialog.Builder(mContext, R.style.ProcessDialog)
43 | .setCancelable(false).create();
44 | View view = View.inflate(mContext, R.layout.update_dialog_layout, null);
45 | forceUpdateDialog.show();
46 | forceUpdateDialog.setContentView(view);
47 | ((TextView) forceUpdateDialog.findViewById(R.id.content_tv)).setText(content);
48 | forceUpdateDialog.findViewById(R.id.confirm_tv).setOnClickListener(new View.OnClickListener() {
49 | @Override
50 | public void onClick(View v) {
51 | v.setEnabled(false);
52 | v.setBackgroundColor(Color.GRAY);
53 | forceUpdateDialog.findViewById(R.id.process_view).setVisibility(View.VISIBLE);
54 | listener.onConfirm();
55 | }
56 | });
57 | forceUpdateDialog.findViewById(R.id.cancel_tv).setVisibility(View.GONE);
58 | }
59 |
60 | static void setForceUpdateDialogProcess(int process) {
61 | if (null != forceUpdateDialog) {
62 | ((DownloadProcessView) forceUpdateDialog.findViewById(R.id.process_view)).setCurrentProcess(process);
63 | }
64 | }
65 |
66 | protected interface OnConfirmListener {
67 | void onConfirm();
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/update/src/main/res/layout/update_dialog_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
19 |
20 |
25 |
26 |
32 |
33 |
42 |
43 |
49 |
50 |
55 |
56 |
68 |
69 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/view/DownloadProcessView.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate.view;
2 |
3 | import android.content.Context;
4 | import android.graphics.Canvas;
5 | import android.graphics.Paint;
6 | import android.graphics.Rect;
7 | import android.util.AttributeSet;
8 | import android.view.View;
9 |
10 | import pers.loren.appupdate.R;
11 |
12 | /**
13 | * Copyright © 2018/12/28 by loren
14 | */
15 | public class DownloadProcessView extends View {
16 |
17 | private Paint paint = new Paint(); // 绘制背景灰色线条画笔
18 | private Paint paintText = new Paint(); // 绘制下载进度画笔
19 | private float offset = 0; // 偏移量
20 | private float maxvalue = 100;
21 | private float currentProcess = 0f;
22 | private Rect mBound = new Rect(); // 获取百分比数字的长宽
23 | private String percentValue = "0%"; // 要显示的现在百分比
24 | private float offsetRight = 0f; // 灰色线条距离右边的距离
25 | private int textSize = 30;
26 | private float offsetTop = 18f; // 距离顶部的偏移量
27 |
28 | public DownloadProcessView(Context context) {
29 | super(context, null);
30 | }
31 |
32 | public DownloadProcessView(Context context, AttributeSet attrs) {
33 | super(context, attrs, 0);
34 | getTextWidth();
35 | }
36 |
37 | public DownloadProcessView(Context context, AttributeSet attrs, int defStyleAttr) {
38 | super(context, attrs, defStyleAttr);
39 | }
40 |
41 | @Override
42 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
43 | setMeasuredDimension(widthMeasureSpec, textSize);
44 | }
45 |
46 | @Override
47 | protected void onDraw(Canvas canvas) {
48 | super.onDraw(canvas);
49 | // 绘制底色
50 | paint.setColor(getResources().getColor(R.color.line));
51 | paint.setStrokeWidth(2);
52 | canvas.drawLine(0, offsetTop, getWidth(), offsetTop, paint);
53 | // 绘制进度条颜色
54 | paint.setColor(getResources().getColor(R.color.download_indicator_color));
55 | paint.setStrokeWidth(3);
56 | canvas.drawLine(0, offsetTop, offset, offsetTop, paint);
57 | // 绘制白色区域及百分比
58 | paint.setColor(getResources().getColor(R.color.text_white));
59 | paint.setStrokeWidth(2);
60 | paintText.setColor(getResources().getColor(R.color.download_indicator_color));
61 | paintText.setTextSize(textSize);
62 | paintText.setAntiAlias(true);
63 | paintText.getTextBounds(percentValue, 0, percentValue.length(), mBound);
64 | canvas.drawLine(offset, offsetTop, offset + mBound.width() + 4, offsetTop, paint);
65 | canvas.drawText(percentValue, offset, offsetTop + mBound.height() / 2 - 2, paintText);
66 | }
67 |
68 | /**
69 | * 设置当前进度值
70 | */
71 | public void setCurrentProcess(int process) {
72 | currentProcess = process;
73 | if (currentProcess < 100) {
74 | percentValue = currentProcess + "%";
75 | } else {
76 | percentValue = "100%";
77 | }
78 | initCurrentProgressBar();
79 | postInvalidate();
80 | }
81 |
82 | /**
83 | * 获取当前进度条长度
84 | */
85 | public void initCurrentProgressBar() {
86 | if (currentProcess < maxvalue) {
87 | offset = ((getWidth() - offsetRight) * currentProcess / maxvalue);
88 | } else {
89 | offset = (getWidth() - offsetRight);
90 | }
91 | }
92 |
93 | /**
94 | * 获取“100%”的宽度
95 | */
96 | public void getTextWidth() {
97 | Paint paint = new Paint();
98 | Rect rect = new Rect();
99 | paint.setTextSize(textSize);
100 | paint.setAntiAlias(true);
101 | paint.getTextBounds("100%", 0, "100%".length(), rect);
102 | offsetRight = rect.width() + 5;
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/AppUpdateManager.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate;
2 |
3 | import android.content.ComponentName;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.ServiceConnection;
7 | import android.os.IBinder;
8 |
9 | import pers.loren.appupdate.interfaces.UpdateDownloadListener;
10 |
11 | /**
12 | * Copyright © 2018/12/28 by loren
13 | */
14 | public class AppUpdateManager {
15 |
16 | private static ServiceConnection sc = null;
17 |
18 | private AppUpdateManager() {
19 | }
20 |
21 | public static void unbindDownloadService(Context context) {
22 | if (sc != null) {
23 | context.unbindService(sc);
24 | }
25 | sc = null;
26 | }
27 |
28 | private static void bindDownloadService(final Context context, final CheckUpdateListener checkUpdateListener) {
29 | if (sc != null) {
30 | unbindDownloadService(context);
31 | }
32 | if (sc == null) {
33 | sc = new ServiceConnection() {
34 | @Override
35 | public void onServiceConnected(ComponentName name, IBinder service) {
36 | if (service != null) {
37 | DownloadService.DownloadBinder binder = ((DownloadService.DownloadBinder) service);
38 | if (!binder.getService().isDownloading) {
39 | checkUpdateListener.onCheckUpdate();
40 | }
41 | } else {
42 | checkUpdateListener.onCheckUpdate();
43 | }
44 | }
45 |
46 | @Override
47 | public void onServiceDisconnected(ComponentName name) {
48 | }
49 | };
50 | }
51 | context.bindService(new Intent(context, DownloadService.class), sc, Context.BIND_AUTO_CREATE);
52 | }
53 |
54 | public static String getUpdateApkPath() {
55 | return DownloadService.APK_PATH;
56 | }
57 |
58 | interface CheckUpdateListener {
59 | void onCheckUpdate();
60 | }
61 |
62 | public static class Builder {
63 | private Context context = null;
64 | //设置下载回调
65 | private UpdateDownloadListener updateDownloadListener = null;
66 | //dialog中升级提示信息
67 | private String updateMessage = "检测到有新的版本";
68 | //下载的url
69 | private String downloadUrl = null;
70 | //是否是强制更新dialog
71 | private boolean forceUpdate = false;
72 | //是否显示自带的dialog
73 | private boolean isShowDialog = true;
74 |
75 | public Builder bind(Context context) {
76 | this.context = context;
77 | return this;
78 | }
79 |
80 | public Builder setDownloadUrl(String url) {
81 | this.downloadUrl = url;
82 | return this;
83 | }
84 |
85 | public Builder setDownloadListener(UpdateDownloadListener updateDownloadListener) {
86 | this.updateDownloadListener = updateDownloadListener;
87 | return this;
88 | }
89 |
90 | public Builder setUpdateMessage(String msg) {
91 | this.updateMessage = msg;
92 | return this;
93 | }
94 |
95 | public Builder setForceUpdate(boolean force) {
96 | this.forceUpdate = force;
97 | return this;
98 | }
99 |
100 | public Builder setShowDialog(boolean show) {
101 | this.isShowDialog = show;
102 | return this;
103 | }
104 |
105 | public void build() {
106 | bindDownloadService(context, new CheckUpdateListener() {
107 | @Override
108 | public void onCheckUpdate() {
109 | if (!isShowDialog) {
110 | startDownload();
111 | } else {
112 | if (forceUpdate) {
113 | UpdateDialog.showUpdateForceDialog(context, updateMessage, new UpdateDialog.OnConfirmListener() {
114 | @Override
115 | public void onConfirm() {
116 | startDownload();
117 | }
118 | });
119 | } else {
120 | UpdateDialog.showUpdateDialog(context, updateMessage, new UpdateDialog.OnConfirmListener() {
121 | @Override
122 | public void onConfirm() {
123 | startDownload();
124 | }
125 | });
126 | }
127 | }
128 | }
129 | });
130 | }
131 |
132 | private void startDownload() {
133 | if (null == context) {
134 | throw new NullPointerException("don't call Builder.bind(context).");
135 | }
136 | if (null == downloadUrl) {
137 | throw new NullPointerException("please call Builder.setDownloadUrl(url).");
138 | }
139 | if (null == updateDownloadListener) {
140 | throw new NullPointerException("please call Builder.setDownloadListener(listener).");
141 | }
142 | DownloadService.updateDownloadListener = this.updateDownloadListener;
143 | Intent intent = new Intent(context.getApplicationContext(), DownloadService.class);
144 | intent.putExtra("url", downloadUrl);
145 | context.startService(intent);
146 | }
147 |
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/README-1.x.md:
--------------------------------------------------------------------------------
1 | # AppUpdate
2 |
3 | 你可以通过它来升级你的App
4 |
5 | ## 简介
6 |
7 | * 小巧便捷 , 使用方便
8 | * 自带强制/非强制性升级提示框 , 可替换弹框的颜色
9 | * HttpURLConnection下载 , 不引用额外的库
10 | * 解决三方库之间FileProvider冲突问题
11 | * 支持Android8.0
12 |
13 | ## 引用
14 |
15 | ```Java
16 | allprojects {
17 | repositories {
18 | ...
19 | maven { url 'https://jitpack.io' }
20 | }
21 | }
22 | ```
23 | ~~~~Java
24 | dependencies {
25 | compile 'com.github.Loren1994:AndroidUpdate:1.2.0'
26 | }
27 | ~~~~
28 |
29 | # 用法
30 | ```java
31 | AppUpdateUtils.bindDownloadService(this, new AppUpdateUtils.CheckUpdateListener() {
32 | @Override
33 | public void checkUpdate() {
34 | //模拟请求接口延时
35 | SystemClock.sleep(3000);
36 | //在这里请求你的检测更新接口
37 | //在接口成功回调里判断是否更新,更新则弹Dialog
38 | UpdateDialog.showUpdateDialog(MainActivity.this,
39 | "update your app", new UpdateDialog.OnConfirmListener() {
40 | @Override
41 | public void onConfirm() {
42 | //下载方法
43 | AppUpdateUtils.update(MainActivity.this,"URL");
44 | }
45 | });
46 | }
47 | });
48 | ```
49 | ## 强制/非强制性升级提示框
50 | ```java
51 | //强制
52 | UpdateDialog.showUpdateForceDialog(MainActivity.this,
53 | "update your app", new UpdateDialog.OnConfirmListener() {
54 | @Override
55 | public void onConfirm() {
56 | Toast.makeText(MainActivity.this,
57 | "confirm", Toast.LENGTH_SHORT).show();
58 | }
59 | });
60 | //非强制
61 | UpdateDialog.showUpdateDialog(MainActivity.this, "update your app",
62 | new UpdateDialog.OnConfirmListener() {
63 | @Override
64 | public void onConfirm() {
65 | Toast.makeText(MainActivity.this,
66 | "confirm",Toast.LENGTH_SHORT).show();
67 | }
68 | });
69 | ```
70 | ### 替换提示框颜色
71 |
72 | ~~~~xml
73 | XXXX
74 | ~~~~
75 |
76 | #### 关于FileProvider冲突的问题
77 |
78 | 以下用TakePhoto 4.0.3测试冲突问题
79 |
80 | ##### TakePhoto库的Provider
81 |
82 | ~~~~Xml
83 |
88 |
91 |
92 | ~~~~
93 |
94 | ##### 测试过程
95 |
96 | | 条件 | 结果 |
97 | | ---------------------------------------- | ----------------------------- |
98 | | app模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" update模块: android:name="android.support.v4.content.FileProvider" | ✘编译不通过 |
99 | | app模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" update模块: android:name=".LorenProvider" | ✔编译通过✘TakePhoto调用崩溃 |
100 | | app模块: android:name="android.support.v4.content.FileProvider" update模块: android:name=".LorenProvider" | ✘编译不通过 |
101 | | app模块: android:name="pers.loren.appupdate.providers.ResolveConflictProvider" update模块: android:name=".LorenProvider" | ✔编译通过✔TakePhoto调用正常✔update库正常 |
102 | | app模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" update模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" | ✔编译通过✘TakePhoto调用崩溃 |
103 | | app模块: android:name="pers.loren.appupdate.providers.ResolveConflictProvider" update模块: android:name=".ResolveConflictProvider" | ✘编译不通过 |
104 |
105 | ##### 冲突报错
106 |
107 | ~~~~Java
108 | Error:Execution failed for task ':app:processDebugManifest'.
109 | > Manifest merger failed : Attribute provider#android.support.v4.content.FileProvider@authorities value=(pers.loren.test.app.fileprovider) from AndroidManifest.xml:26:13-68
110 | is also present at [com.jph.takephoto:takephoto_library:4.0.3] AndroidManifest.xml:19:13-64 value=(pers.loren.test.fileprovider).
111 | Suggestion: add 'tools:replace="android:authorities"' to element at AndroidManifest.xml:24:9-32:20 to override.
112 | ~~~~
113 |
114 | ##### 最终Manifest
115 |
116 | ~~~~xml
117 |
118 |
123 |
126 |
127 |
128 |
129 |
134 |
137 |
138 | ~~~~
139 |
140 | ##### 最终解决方案
141 |
142 | update库里采用自定义的fileprovider , app模块里也需要写provider标签, update模块提供ResolveConflictProvider以便app模块使用 , app模块里也可以自行建立fileprovider类
143 |
144 | #### 一点总结
145 |
146 | * 同一App的多个库的provider的name都是android.support.v4.content.FileProvider时会引起冲突
147 | * 上述情况可以通过写自定义FileProvider解决
148 | * 同一App不同库的provider的name用同一个自定义FileProvider也会引起冲突
149 | * 不同App之间provider的name可以相同 , 但authorities不可以重复,否则后者App不能安装
150 | * 三方库的Manifest里引入tools , app里也引入了tools , 可能导致merge manifest fail
151 |
152 | #### 一点题外总结
153 |
154 | 设置applicationId时 :
155 |
156 | "pers.loren.test" : ✔ 成功
157 |
158 | "pers.loren.test.1" : ✘ 编译通过 , install时提示解析安装包失败 (Android6.0)
159 |
160 | "pers.loren.test1" : ✔ 成功
161 |
162 | # Tips
163 |
164 | * 如果只引用这一个带有provider的库 , 则app里不需要写provider
165 | * 如果库之间有冲突 , 则参考 [最终Manifest]( #最终Manifest )
166 | * AppUpdateUtils.bindDownloadService( ) : service不为null会自动解绑
167 | * 不要忘记在onDestory( )里调用AppUpdateUtils.unbindDownloadService( )解绑Service
168 |
169 | ### 项目地址
170 |
171 | GitHub:https://github.com/Loren1994/AndroidUpdate 欢迎star~ issue~
172 |
173 |
174 |
175 |
176 | # <(▰˘◡˘▰)>
177 |
178 |
179 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AppUpdate
2 |
3 | ##### 👉🏼[前往1.x文档](https://github.com/Loren1994/AndroidUpdate/blob/master/README-1.x.md)
4 |
5 | 你可以通过它来升级你的App。
6 |
7 | ##### [](https://jitpack.io/#Loren1994/AndroidUpdate) [](https://android-arsenal.com/api?level=16)
8 |
9 | ### 简介
10 |
11 | * 小巧便捷 , 使用方便
12 | * 自带强制/非强制性升级提示框 , 可替换弹框的颜色
13 | * HttpURLConnection下载 , 不引用额外的库
14 | * 解决三方库之间FileProvider冲突问题
15 | * 支持Android 8
16 |
17 | ### 🔥2.x版本🔥
18 |
19 | - [x] 重构API,调用方式更加简单
20 |
21 | - [x] 支持使用自定义弹框
22 |
23 | - [x] 升级库的support依赖
24 |
25 | - [x] 支持进度回调,对话框进度条,通知栏进度条展示
26 |
27 | - [x] 支持后台下载
28 |
29 | - [x] 支持强制更新
30 |
31 | - [x] 支持弹出框颜色替换
32 |
33 | ### Gradle引入
34 |
35 | ```Java
36 | allprojects {
37 | repositories {
38 | ...
39 | maven { url 'https://jitpack.io' }
40 | }
41 | }
42 | ```
43 | ~~~~Java
44 | dependencies {
45 | implementation 'com.github.Loren1994:AndroidUpdate:2.0.2'
46 | }
47 | ~~~~
48 |
49 | ### API
50 |
51 | ```java
52 | //首先请求你的检测更新接口 - 判断是否更新
53 | new AppUpdateManager.Builder()
54 | .bind(this) //必须调用
55 | .setDownloadUrl(url) //必须设置
56 | .setDownloadListener(new UpdateDownloadListener() { //必须设置
57 | @Override
58 | public void onDownloading(int process) {
59 | Log.d("update", "onProcess: " + process);
60 | }
61 |
62 | @Override
63 | public void onDownloadSuccess() {
64 | Log.d("update", "下载完成");
65 | }
66 |
67 | @Override
68 | public void onDownloadFail(String reason) {
69 | Log.d("update", reason);
70 | }
71 | })
72 | .setUpdateMessage("检测到有新的版本,请下载升级.") //自带弹框显示的内容
73 | .setShowDialog(true) //是否显示自带的弹框
74 | .setForceUpdate(true) //是否显示自带的强制弹框
75 | .build();
76 | ```
77 | ### 说明
78 |
79 | > ⚠️ 所需相关权限需要在自己的App中申请。
80 | >
81 | > ⚠️ 库中带有两种提示框,分为强制性更新框和非强制性更新框,可通过setForceUpdate设置。
82 | >
83 | > ⚠️ 若不使用自带的提示框,可设置setShowDialog(false)不显示弹框,则AppUpdateManager可看做只是下载的方法。在这之前加入自己的弹框和页面逻辑即可。
84 |
85 | * 强制弹框
86 |
87 | 
88 |
89 | * 非强制弹框
90 |
91 | 
92 |
93 | ### 替换提示框颜色
94 |
95 | ~~~~xml
96 | XXXX
97 | ~~~~
98 |
99 | ### 关于FileProvider冲突的问题
100 |
101 | 以下用TakePhoto 4.0.3测试冲突问题
102 |
103 | ##### TakePhoto库的Provider
104 |
105 | ~~~~Xml
106 |
111 |
114 |
115 | ~~~~
116 |
117 | ##### 测试过程
118 |
119 | | 条件 | 结果 |
120 | | ---------------------------------------- | ----------------------------- |
121 | | app模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" update模块: android:name="android.support.v4.content.FileProvider" | ✘编译不通过 |
122 | | app模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" update模块: android:name=".LorenProvider" | ✔编译通过✘TakePhoto调用崩溃 |
123 | | app模块: android:name="android.support.v4.content.FileProvider" update模块: android:name=".LorenProvider" | ✘编译不通过 |
124 | | app模块: android:name="pers.loren.appupdate.providers.ResolveConflictProvider" update模块: android:name=".LorenProvider" | ✔编译通过✔TakePhoto调用正常✔update库正常 |
125 | | app模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" update模块: tools:replace="android:authorities" android:name="android.support.v4.content.FileProvider" | ✔编译通过✘TakePhoto调用崩溃 |
126 | | app模块: android:name="pers.loren.appupdate.providers.ResolveConflictProvider" update模块: android:name=".ResolveConflictProvider" | ✘编译不通过 |
127 |
128 | ##### 冲突报错
129 |
130 | ~~~~Java
131 | Error:Execution failed for task ':app:processDebugManifest'.
132 | > Manifest merger failed : Attribute provider#android.support.v4.content.FileProvider@authorities value=(pers.loren.test.app.fileprovider) from AndroidManifest.xml:26:13-68
133 | is also present at [com.jph.takephoto:takephoto_library:4.0.3] AndroidManifest.xml:19:13-64 value=(pers.loren.test.fileprovider).
134 | Suggestion: add 'tools:replace="android:authorities"' to element at AndroidManifest.xml:24:9-32:20 to override.
135 | ~~~~
136 |
137 | ##### 最终Manifest
138 |
139 | ~~~~xml
140 |
141 |
146 |
149 |
150 |
151 |
152 |
157 |
160 |
161 | ~~~~
162 |
163 | ##### 最终解决方案
164 |
165 | update库里采用自定义的fileprovider , app模块里也需要写provider标签, update模块提供ResolveConflictProvider以便app模块使用 , app模块里也可以自行建立fileprovider类
166 |
167 | ### 一点总结
168 |
169 | * 同一App的多个库的provider的name都是android.support.v4.content.FileProvider时会引起冲突
170 | * 上述情况可以通过写自定义FileProvider解决
171 | * 同一App不同库的provider的name用同一个自定义FileProvider也会引起冲突
172 | * 不同App之间provider的name可以相同 , 但authorities不可以重复,否则后者App不能安装
173 | * 三方库的Manifest里引入tools , app里也引入了tools , 可能导致merge manifest fail
174 |
175 | ### Tips
176 |
177 | * 如果只引用这一个带有provider的库 , 则app里不需要写provider
178 | * 如果库之间有冲突 , 则参考 [最终Manifest]( #最终Manifest )
179 | * build()方法里已判断ServiceConnection不为null时首先解绑
180 | * 可以调用AppUpdateManager.unbindDownloadService(this)解绑Service
181 |
182 | ### 项目地址
183 |
184 | GitHub:https://github.com/Loren1994/AndroidUpdate 欢迎star~ issue~
185 |
186 |
187 |
188 |
189 | # <(▰˘◡˘▰)>
190 |
191 |
192 |
--------------------------------------------------------------------------------
/update/src/main/java/pers/loren/appupdate/DownloadService.java:
--------------------------------------------------------------------------------
1 | package pers.loren.appupdate;
2 |
3 | import android.app.IntentService;
4 | import android.app.Notification;
5 | import android.app.NotificationChannel;
6 | import android.app.NotificationManager;
7 | import android.app.PendingIntent;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.net.Uri;
11 | import android.os.Binder;
12 | import android.os.Build;
13 | import android.os.Environment;
14 | import android.os.IBinder;
15 | import android.support.annotation.Nullable;
16 | import android.support.v4.app.NotificationCompat.Builder;
17 | import android.support.v4.content.FileProvider;
18 | import android.util.Log;
19 |
20 | import java.io.File;
21 | import java.io.FileOutputStream;
22 | import java.io.IOException;
23 | import java.io.InputStream;
24 | import java.net.HttpURLConnection;
25 | import java.net.URL;
26 |
27 | import pers.loren.appupdate.interfaces.UpdateDownloadListener;
28 |
29 | public class DownloadService extends IntentService {
30 | private static final String NOTIFICATION_CHANNEL = "DownloadChannel";
31 | public static String APK_PATH = Environment.getExternalStorageDirectory() + "/update.apk";
32 | public static UpdateDownloadListener updateDownloadListener = null;
33 | private final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
34 | private final String TAG = "DownloadService";
35 | private final int NOTIFICATION_ID = 0;
36 | // public static String AUTHORITY = BuildConfig.APPLICATION_ID + "appupdate.fileprovider";
37 | public boolean isDownloading = false;
38 | private Builder mBuilder;
39 | private NotificationManager mNotifyManager;
40 | private DownloadBinder downloadBinder;
41 |
42 | public DownloadService() {
43 | super("DownloadService");
44 | }
45 |
46 | @Nullable
47 | @Override
48 | public IBinder onBind(Intent intent) {
49 | if (downloadBinder == null) {
50 | downloadBinder = new DownloadBinder();
51 | }
52 | return downloadBinder;
53 | }
54 |
55 | @Override
56 | protected void onHandleIntent(Intent intent) {
57 | mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
58 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
59 | NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, "下载",
60 | NotificationManager.IMPORTANCE_HIGH);
61 | channel.setDescription("下载升级文件");
62 | channel.enableVibration(false);
63 | channel.enableLights(false);
64 | mNotifyManager.createNotificationChannel(channel);
65 | }
66 | mBuilder = new Builder(this, NOTIFICATION_CHANNEL);
67 | String appName = getString(getApplicationInfo().labelRes);
68 | int icon = getApplicationInfo().icon;
69 | mBuilder.setContentTitle(appName).setSmallIcon(icon);
70 | String urlStr = intent.getStringExtra("url");
71 | InputStream in = null;
72 | FileOutputStream out = null;
73 | try {
74 | URL url = new URL(urlStr);
75 | HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
76 | urlConnection.setRequestMethod("GET");
77 | urlConnection.setDoOutput(false);
78 | urlConnection.setConnectTimeout(10 * 1000);
79 | urlConnection.setReadTimeout(10 * 1000);
80 | urlConnection.setRequestProperty("Connection", "Keep-Alive");
81 | urlConnection.setRequestProperty("Charset", "UTF-8");
82 | urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
83 | urlConnection.connect();
84 | long byteTotal = urlConnection.getContentLength();
85 | long byteSum = 0;
86 | int byteRead;
87 | in = urlConnection.getInputStream();
88 | // File dir = StorageUtils.getCacheDirectory(this);
89 | // String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());
90 | File apkFile = new File(APK_PATH);
91 | if (!apkFile.exists()) {
92 | Log.i(TAG, "file create success:" + apkFile.createNewFile());
93 | }
94 | // File apkFile = new File(dir, apkName);
95 | out = new FileOutputStream(apkFile);
96 | byte[] buffer = new byte[BUFFER_SIZE];
97 | isDownloading = true;
98 | int oldProgress = 0;
99 | updateProgress(0);
100 | while ((byteRead = in.read(buffer)) != -1) {
101 | byteSum += byteRead;
102 | out.write(buffer, 0, byteRead);
103 | int progress = (int) (byteSum * 100L / byteTotal);
104 | // 如果进度与之前进度相等,则不更新,如果更新太频繁,否则会造成界面卡顿
105 | if (progress != oldProgress) {
106 | updateProgress(progress);
107 | UpdateDialog.setForceUpdateDialogProcess(progress);
108 | if (null != updateDownloadListener)
109 | updateDownloadListener.onDownloading(progress);
110 | }
111 | oldProgress = progress;
112 | }
113 | // 下载完成
114 | isDownloading = false;
115 | if (null != updateDownloadListener)
116 | updateDownloadListener.onDownloadSuccess();
117 | installAPk(apkFile);
118 | mNotifyManager.cancel(NOTIFICATION_ID);
119 | } catch (Exception e) {
120 | isDownloading = false;
121 | if (null != updateDownloadListener)
122 | updateDownloadListener.onDownloadFail(e.getMessage());
123 | mNotifyManager.cancel(NOTIFICATION_ID);
124 | e.printStackTrace();
125 | } finally {
126 | if (out != null) {
127 | try {
128 | out.close();
129 | } catch (IOException e1) {
130 | e1.printStackTrace();
131 | }
132 | }
133 | if (in != null) {
134 | try {
135 | in.close();
136 | } catch (IOException e2) {
137 | e2.printStackTrace();
138 | }
139 | }
140 | }
141 | }
142 |
143 | private void updateProgress(int progress) {
144 | // "正在下载:" + progress + "%"
145 | mBuilder.setContentText(this.getString(R.string.android_auto_update_download_progress, progress)).setProgress(100, progress, false);
146 | // setContentIntent如果不设置在4.0+上没有问题,在4.0以下会报异常
147 | PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
148 | mBuilder.setContentIntent(pendingintent);
149 | Notification notification = mBuilder.build();
150 | notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
151 | mNotifyManager.notify(NOTIFICATION_ID, notification);
152 | }
153 |
154 | private void installAPk(File apkFile) {
155 | Intent intent = new Intent(Intent.ACTION_VIEW);
156 | // 如果没有设置SDCard写权限,或者没有sdcard,apk文件保存在内存中,需要授予权限才能安装
157 | try {
158 | String[] command = {"chmod", "777", apkFile.toString()};
159 | ProcessBuilder builder = new ProcessBuilder(command);
160 | builder.start();
161 | } catch (IOException e) {
162 | e.printStackTrace();
163 | }
164 | Uri uri;
165 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
166 | uri = Uri.fromFile(apkFile);
167 | } else {
168 | uri = FileProvider.getUriForFile(getApplicationContext(), this.getPackageName() + ".appupdate.fileprovider", apkFile);
169 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
170 | }
171 | intent.setDataAndType(uri, "application/vnd.android.package-archive");
172 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
173 | startActivity(intent);
174 | }
175 |
176 | class DownloadBinder extends Binder {
177 | DownloadService getService() {
178 | return DownloadService.this;
179 | }
180 | }
181 | }
182 |
--------------------------------------------------------------------------------