From 253b924066851dcf08f24017e981a3ceb0592b7d Mon Sep 17 00:00:00 2001 From: AllenLiu <29949821@qq.com> Date: Wed, 11 Dec 2019 16:26:51 +0800 Subject: [PATCH 1/5] =?UTF-8?q?mod=20=E5=81=9C=E6=AD=A2=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E6=97=B6=E9=94=80=E6=AF=81builder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 3 +++ .../versionchecklib/v2/builder/DownloadBuilder.java | 6 ++++++ sample/build.gradle | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index ba213bd..33863fc 100644 --- a/build.gradle +++ b/build.gradle @@ -21,9 +21,12 @@ buildscript { allprojects { repositories { jcenter() + maven { url "https://jitpack.io" } maven { url 'https://maven.google.com/' name 'Google' + + } } } diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java index 873105f..a1573cf 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java @@ -346,6 +346,12 @@ public void destory() { setForceUpdateListener(null); setApkDownloadListener(null); setOnCancelListener(null); + setReadyDownloadCommitClickListener(null); + setDownloadFailedCommitClickListener(null); + setReadyDownloadCancelListener(null); + setDownloadingCancelListener(null); + setDownloadFailedCancelListener(null); + if (getRequestVersionBuilder() != null) getRequestVersionBuilder().destory(); requestVersionBuilder = null; diff --git a/sample/build.gradle b/sample/build.gradle index 50f1c90..e872740 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -2,7 +2,6 @@ apply plugin: 'com.android.application' //apply plugin: 'me.tatarka.retrolambda' android { compileSdkVersion 28 - buildToolsVersion "28.0.2" defaultConfig { applicationId "com.allenliu.sample" minSdkVersion 16 @@ -30,6 +29,7 @@ dependencies { implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' implementation project(':library') +// implementation 'com.github.AlexLiuSheng:CheckVersionLib:2.2.2' // compile 'com.allenliu.versionchecklib:library:2.0.9' implementation 'androidx.appcompat:appcompat:1.1.0' // compile 'com.allenliu.versionchecklib:library:1.7.6' From a9424f3fcb04652e10573b92854ab72a924d40c9 Mon Sep 17 00:00:00 2001 From: AllenLiu <29949821@qq.com> Date: Wed, 11 Dec 2019 16:41:59 +0800 Subject: [PATCH 2/5] mod readme --- README.md | 4 ++-- README_UN.MD | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 56be316..d56abc1 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ The strongest feature is easier to integrate than version of V1.+ #### jcenter ``` -implementation 'com.allenliu.versionchecklib:library:2.2.2' +implementation 'com.allenliu.versionchecklib:library:2.2.3' ``` #### jitpack && androiud x ``` @@ -39,7 +39,7 @@ allprojects { } } dependencies { - implementation 'com.github.AlexLiuSheng:CheckVersionLib:2.2.2' + implementation 'com.github.AlexLiuSheng:CheckVersionLib:2.2.3' } ``` diff --git a/README_UN.MD b/README_UN.MD index 9307a8f..2c3191e 100644 --- a/README_UN.MD +++ b/README_UN.MD @@ -27,7 +27,7 @@ #### jcenter ``` -implementation 'com.allenliu.versionchecklib:library:2.2.2' +implementation 'com.allenliu.versionchecklib:library:2.2.3' ``` #### jitpack && androiud x ``` @@ -38,7 +38,7 @@ allprojects { } } dependencies { - implementation 'com.github.AlexLiuSheng:CheckVersionLib:2.2.2' + implementation 'com.github.AlexLiuSheng:CheckVersionLib:2.2.3' } ``` From a71768f367c8d326d13da92c7df866d844f5f1e8 Mon Sep 17 00:00:00 2001 From: ALECKLQ <29949821@qq.com> Date: Mon, 13 Apr 2020 16:53:10 +0800 Subject: [PATCH 3/5] fix request external storage permission error on android Q fix okhttp ssl factory error on android q --- library/build.gradle | 8 +-- library/src/main/AndroidManifest.xml | 1 + .../versionchecklib/core/http/AllenHttp.java | 8 +-- .../versionchecklib/utils/FileHelper.java | 68 +++++++++++++------ .../v2/builder/DownloadBuilder.java | 17 ++++- .../v2/builder/VersionCheckBinder.java | 1 + .../versionchecklib/v2/ui/VersionService.java | 3 +- sample/build.gradle | 4 +- .../com/allenliu/sample/v2/V2Activity.java | 4 +- 9 files changed, 77 insertions(+), 37 deletions(-) diff --git a/library/build.gradle b/library/build.gradle index 19c5a68..7e8a7df 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -1,11 +1,11 @@ apply plugin: 'com.android.library' android { - compileSdkVersion 28 - buildToolsVersion "28.0.3" + compileSdkVersion 29 + buildToolsVersion "29.0.3" resourcePrefix "versionchecklib" defaultConfig { minSdkVersion 14 - targetSdkVersion 28 + targetSdkVersion 29 versionCode 1 versionName version } @@ -25,7 +25,7 @@ android { dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.appcompat:appcompat:1.1.0' - implementation 'com.squareup.okhttp3:okhttp:3.14.2' + implementation 'com.squareup.okhttp3:okhttp:4.3.1' implementation 'org.greenrobot:eventbus:3.1.1' } diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml index 10676e1..a020df9 100644 --- a/library/src/main/AndroidManifest.xml +++ b/library/src/main/AndroidManifest.xml @@ -13,6 +13,7 @@ T assembleHeader(T builder, RequestVe } public static Request.Builder get(RequestVersionBuilder versionParams) { Request.Builder builder = new Request.Builder(); - builder = assembleHeader(builder, versionParams); + assembleHeader(builder, versionParams); builder.url(assembleUrl(versionParams.getRequestUrl(), versionParams.getRequestParams())); return builder; @@ -191,7 +191,7 @@ public static Request.Builder get(RequestVersionBuilder versionParams) { public static Request.Builder post(RequestVersionBuilder versionParams) { FormBody formBody = getRequestParams(versionParams); Request.Builder builder = new Request.Builder(); - builder = assembleHeader(builder, versionParams); + assembleHeader(builder, versionParams); builder.post(formBody).url(versionParams.getRequestUrl()); return builder; } @@ -201,7 +201,7 @@ public static Request.Builder postJson(RequestVersionBuilder versionParams) { String json = getRequestParamsJson(versionParams.getRequestParams()); RequestBody body = RequestBody.create(JSON, json); Request.Builder builder = new Request.Builder(); - builder = assembleHeader(builder, versionParams); + assembleHeader(builder, versionParams); builder.post(body).url(versionParams.getRequestUrl()); return builder; } diff --git a/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java b/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java index c0e29aa..10592e6 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java +++ b/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java @@ -1,41 +1,67 @@ package com.allenliu.versionchecklib.utils; +import android.content.Context; import android.os.Environment; import java.io.File; +import androidx.annotation.NonNull; + public class FileHelper { + @Deprecated + public static String getDownloadApkCachePath() { + + String appCachePath = null; + + + if (checkSDCard()) { + + appCachePath = Environment.getExternalStorageDirectory() + "/AllenVersionPath/"; + } else { + appCachePath = Environment.getDataDirectory().getPath() + "/AllenVersionPath/"; + } + File file = new File(appCachePath); + if (!file.exists()) { + file.mkdirs(); + } + return appCachePath; + } - public static String getDownloadApkCachePath() { + public static String getDownloadApkCachePath(Context context) { + String appCachePath; + if (checkSDCard()) { + appCachePath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/AllenVersionPath/"; - String appCachePath = null; + } else { + appCachePath = context.getFilesDir().getAbsolutePath() + "/AllenVersionPath/"; + } - if (checkSDCard()) { - appCachePath = Environment.getExternalStorageDirectory() + "/AllenVersionPath/" ; - } else { - appCachePath = Environment.getDataDirectory().getPath() + "/AllenVersionPath/" ; - } - File file = new File(appCachePath); - if (!file.exists()) { - file.mkdirs(); - } - return appCachePath; - } + File file = new File(appCachePath); + if (!file.exists()) { + file.mkdirs(); + } + return appCachePath; + } - /** - * - */ - public static boolean checkSDCard() { - boolean sdCardExist = Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED); + /** + * + */ + private static boolean checkSDCard() { - return sdCardExist; + return Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED); - } + } + public static String dealDownloadPath(@NonNull String downloadAPKPath) { + if (!downloadAPKPath.endsWith(File.separator)) { + downloadAPKPath += File.separator; + } + return downloadAPKPath; + } } \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java index a1573cf..7d8d3ad 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java @@ -3,6 +3,8 @@ import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; +import android.os.Environment; + import androidx.annotation.NonNull; import com.allenliu.versionchecklib.callback.APKDownloadListener; @@ -58,14 +60,14 @@ public DownloadBuilder() { private void initialize() { isSilentDownload = false; - downloadAPKPath = FileHelper.getDownloadApkCachePath(); +// downloadAPKPath = FileHelper.getDownloadApkCachePath(); isForceRedownload = false; isShowDownloadingDialog = true; isShowNotification = true; isDirectDownload = false; isShowDownloadFailDialog = true; notificationBuilder = NotificationBuilder.create(); - runOnForegroundService=true; + runOnForegroundService = true; } public DownloadBuilder(RequestVersionBuilder requestVersionBuilder, UIData versionBundle) { @@ -309,6 +311,7 @@ public void executeMission(Context context) { if (apkName == null) { apkName = context.getApplicationContext().getPackageName(); } + if (notificationBuilder.getIcon() == 0) { final PackageManager pm = context.getPackageManager(); final ApplicationInfo applicationInfo; @@ -320,6 +323,9 @@ public void executeMission(Context context) { e.printStackTrace(); } } + //fix path permission + setupDownloadPath(context); +// downloadAPKPath=context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() + "/"; if (checkWhetherNeedRequestVersion()) { RequestVersionManager.getInstance().requestVersion(this, context.getApplicationContext()); } else { @@ -328,6 +334,13 @@ public void executeMission(Context context) { } + private void setupDownloadPath(Context context) { + if (downloadAPKPath == null) { + downloadAPKPath = FileHelper.getDownloadApkCachePath(context); + } + downloadAPKPath = FileHelper.dealDownloadPath(downloadAPKPath); + } + public void download(Context context) { VersionService.enqueueWork(context.getApplicationContext(), this); } diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java index 407cded..f339b70 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java @@ -2,6 +2,7 @@ import android.content.ServiceConnection; import android.os.Binder; +import android.os.Environment; import com.allenliu.versionchecklib.v2.ui.VersionService; diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java index 6d7343d..bebc86e 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java @@ -88,13 +88,12 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } - ALog.e("version service create"); //https://issuetracker.google.com/issues/76112072 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForeground(NotificationHelper.NOTIFICATION_ID, NotificationHelper.createSimpleNotification(this)); // init(); - return super.onStartCommand(intent, flags, startId); + return START_REDELIVER_INTENT; } @Override diff --git a/sample/build.gradle b/sample/build.gradle index e872740..daf9fa3 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -1,11 +1,11 @@ apply plugin: 'com.android.application' //apply plugin: 'me.tatarka.retrolambda' android { - compileSdkVersion 28 + compileSdkVersion 29 defaultConfig { applicationId "com.allenliu.sample" minSdkVersion 16 - targetSdkVersion 28 + targetSdkVersion 29 versionCode 1 versionName "1.0" diff --git a/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java b/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java index a5872fd..c663add 100644 --- a/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java +++ b/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java @@ -181,8 +181,8 @@ public void onCancel() { builder.setCustomDownloadFailedListener(createCustomDownloadFailedDialog()); break; } - //自定义下载路径 - builder.setDownloadAPKPath(Environment.getExternalStorageDirectory() + "/ALLEN/AllenVersionPath2/"); + //自定义下载路径.在Android Q以上,请将路径设置为app内部路径,不要随便设置 +// builder.setDownloadAPKPath(Environment.getExternalStorageDirectory() + "/ALLEN/AllenVersionPath2"); String address = etAddress.getText().toString(); if (!"".equals(address)) builder.setDownloadAPKPath(address); From 5b60324cac7fa8e5662e975c7be22d3e8b021fb5 Mon Sep 17 00:00:00 2001 From: shengliu7 <29949821@qq.com> Date: Sat, 19 Dec 2020 15:11:03 +0800 Subject: [PATCH 4/5] feat:use kotlin implementation some class and fix bugs --- build.gradle | 4 + library/build.gradle | 2 + library/src/main/AndroidManifest.xml | 2 +- .../callback/DownloadListener.java | 2 +- .../core/VersionDialogActivity.java | 1 + .../v2/builder/BuilderManager.java | 32 -- .../v2/builder/BuilderManager.kt | 71 ++++ .../v2/builder/DownloadBuilder.java | 23 +- .../v2/builder/RequestVersionBuilder.java | 4 +- .../v2/builder/VersionCheckBinder.java | 37 -- .../v2/callback/DownloadListenerKt.kt | 13 + .../v2/callback/LifecycleListener.kt | 16 + .../v2/callback/RequestVersionListener.java | 2 +- .../v2/net/DownloadMangerV2.java | 81 +---- .../v2/net/RequestVersionManager.java | 60 ++-- .../v2/ui/AllenBaseActivity.java | 139 ------- .../v2/ui/AllenBaseActivity.kt | 123 +++++++ .../versionchecklib/v2/ui/BuilderHelper.java | 49 --- .../v2/ui/DownloadFailedActivity.java | 115 ------ .../v2/ui/DownloadFailedActivity.kt | 93 +++++ .../v2/ui/DownloadingActivity.java | 167 --------- .../v2/ui/DownloadingActivity.kt | 153 ++++++++ .../v2/ui/NotificationHelper.java | 200 ----------- .../v2/ui/NotificationHelper.kt | 207 +++++++++++ .../versionchecklib/v2/ui/UIActivity.java | 179 --------- .../versionchecklib/v2/ui/UIActivity.kt | 146 ++++++++ .../versionchecklib/v2/ui/VersionService.java | 340 ------------------ .../versionchecklib/v2/ui/VersionService.kt | 295 +++++++++++++++ 28 files changed, 1158 insertions(+), 1398 deletions(-) delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/builder/BuilderManager.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/builder/BuilderManager.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/callback/DownloadListenerKt.kt create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/callback/LifecycleListener.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/BuilderHelper.java delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.kt delete mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java create mode 100644 library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt diff --git a/build.gradle b/build.gradle index 33863fc..ae3f5bd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,8 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + ext.kotlin_version = "1.4.0" + repositories { jcenter() maven { @@ -10,6 +12,8 @@ buildscript { } dependencies { classpath 'com.android.tools.build:gradle:3.5.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + // classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0' // classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' // classpath 'me.tatarka:gradle-retrolambda:3.2.5' diff --git a/library/build.gradle b/library/build.gradle index 7e8a7df..c4ed90b 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -1,4 +1,6 @@ apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 29 buildToolsVersion "29.0.3" diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml index a020df9..936f842 100644 --- a/library/src/main/AndroidManifest.xml +++ b/library/src/main/AndroidManifest.xml @@ -39,7 +39,7 @@ android:name=".core.MyService" android:enabled="true" - android:exported="true" /> + android:exported="false" /> doWhenNotNull(nullBlock: (() -> T)? = null, block: DownloadBuilder.() -> T): T? { + val builder = downloadBuilder + if (builder != null) { + return builder.block() + + } else { + nullBlock?.invoke() + AllenVersionChecker.getInstance().cancelAllMission() + } + return null + } + +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java index 7d8d3ad..1bbbe07 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java @@ -3,7 +3,6 @@ import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; -import android.os.Environment; import androidx.annotation.NonNull; @@ -309,7 +308,8 @@ public DownloadBuilder setDirectDownload(boolean directDownload) { public void executeMission(Context context) { if (apkName == null) { - apkName = context.getApplicationContext().getPackageName(); + //https://github.com/AlexLiuSheng/CheckVersionLib/issues/338 + apkName = context.getApplicationContext().getPackageName().replaceAll("\\.", ""); } if (notificationBuilder.getIcon() == 0) { @@ -342,7 +342,7 @@ private void setupDownloadPath(Context context) { } public void download(Context context) { - VersionService.enqueueWork(context.getApplicationContext(), this); + VersionService.Companion.enqueueWork(context.getApplicationContext(), this); } private boolean checkWhetherNeedRequestVersion() { @@ -352,21 +352,4 @@ private boolean checkWhetherNeedRequestVersion() { return false; } - public void destory() { - setCustomDownloadFailedListener(null); - setCustomDownloadingDialogListener(null); - setCustomVersionDialogListener(null); - setForceUpdateListener(null); - setApkDownloadListener(null); - setOnCancelListener(null); - setReadyDownloadCommitClickListener(null); - setDownloadFailedCommitClickListener(null); - setReadyDownloadCancelListener(null); - setDownloadingCancelListener(null); - setDownloadFailedCancelListener(null); - - if (getRequestVersionBuilder() != null) - getRequestVersionBuilder().destory(); - requestVersionBuilder = null; - } } diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/RequestVersionBuilder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/RequestVersionBuilder.java index a590b05..db2d3dd 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/RequestVersionBuilder.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/RequestVersionBuilder.java @@ -70,8 +70,6 @@ public DownloadBuilder request(RequestVersionListener requestVersionListener) { return new DownloadBuilder(this, null); } - public void destory() { - requestVersionListener = null; - } + } diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java deleted file mode 100644 index f339b70..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/VersionCheckBinder.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.allenliu.versionchecklib.v2.builder; - -import android.content.ServiceConnection; -import android.os.Binder; -import android.os.Environment; - -import com.allenliu.versionchecklib.v2.ui.VersionService; - -/** - * @author AllenLiu - * @date 2019/9/20 - */ -public class VersionCheckBinder extends Binder { - private VersionService versionService; - private ServiceConnection serviceConnection; - - public VersionCheckBinder(VersionService versionService) { - this.versionService = versionService; - - } - - public VersionCheckBinder setServiceConnection(ServiceConnection serviceConnection) { - this.serviceConnection = serviceConnection; - return this; - } - - public ServiceConnection getServiceConnection() { - return serviceConnection; - } - - public VersionCheckBinder setDownloadBuilder(DownloadBuilder downloadBuilder) { - versionService.setBuilder(downloadBuilder); - versionService.init(); - return this; - } - -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/callback/DownloadListenerKt.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/callback/DownloadListenerKt.kt new file mode 100644 index 0000000..01f40e2 --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/callback/DownloadListenerKt.kt @@ -0,0 +1,13 @@ +package com.allenliu.versionchecklib.v2.callback + +import com.allenliu.versionchecklib.callback.DownloadListener + +/** + * @author : shengliu7 + * @e-mail : shengliu7@iflytek.com + * @date : 2020/12/19 2:51 PM + * @desc : + * + */ +interface DownloadListenerKt : DownloadListener, LifecycleListener { +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/callback/LifecycleListener.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/callback/LifecycleListener.kt new file mode 100644 index 0000000..0c16553 --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/callback/LifecycleListener.kt @@ -0,0 +1,16 @@ +package com.allenliu.versionchecklib.v2.callback + +import com.allenliu.versionchecklib.v2.builder.BuilderManager + +/** + * @author : shengliu7 + * @e-mail : shengliu7@iflytek.com + * @date : 2020/12/19 2:18 PM + * @desc : + * + */ +interface LifecycleListener { + fun isDisposed() = + BuilderManager.getDownloadBuilder() == null + +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/callback/RequestVersionListener.java b/library/src/main/java/com/allenliu/versionchecklib/v2/callback/RequestVersionListener.java index bc59d0a..1e43d9c 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/callback/RequestVersionListener.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/callback/RequestVersionListener.java @@ -9,7 +9,7 @@ * Created by allenliu on 2018/1/12. */ -public interface RequestVersionListener { +public interface RequestVersionListener { /** * @param result the result string of request * @return developer should return version bundle ,to use when showing UI page,could be null diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/net/DownloadMangerV2.java b/library/src/main/java/com/allenliu/versionchecklib/v2/net/DownloadMangerV2.java index 44d74c8..0ab864e 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/net/DownloadMangerV2.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/net/DownloadMangerV2.java @@ -3,14 +3,11 @@ import android.os.Handler; import android.os.Looper; -import com.allenliu.versionchecklib.callback.DownloadListener; import com.allenliu.versionchecklib.core.http.AllenHttp; import com.allenliu.versionchecklib.core.http.FileCallBack; +import com.allenliu.versionchecklib.v2.callback.DownloadListenerKt; import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; import okhttp3.Call; import okhttp3.Request; @@ -21,7 +18,7 @@ */ public class DownloadMangerV2 { - public static void download(final String url, final String downloadApkPath, final String fileName, final DownloadListener listener) { + public static void download(final String url, final String downloadApkPath, final String fileName, final DownloadListenerKt listener) { if (url != null && !url.isEmpty()) { Request request = new Request .Builder() @@ -31,7 +28,7 @@ public static void download(final String url, final String downloadApkPath, fina new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if (listener != null) + if (listener != null && !listener.isDisposed()) listener.onCheckerStartDownload(); } }); @@ -42,7 +39,7 @@ public void onSuccess(final File file, Call call, Response response) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if (listener != null) + if (listener != null && !listener.isDisposed()) listener.onCheckerDownloadSuccess(file); } }); @@ -53,7 +50,7 @@ public void onDownloading(final int progress) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if (listener != null) + if (listener != null && !listener.isDisposed()) listener.onCheckerDownloading(progress); } }); @@ -71,76 +68,12 @@ public void onDownloadFailed() { } } - private static void response(Response response, String downloadApkPath, String fileName, final DownloadListener listener) { - if (response.isSuccessful()) { - InputStream is = null; - byte[] buf = new byte[2048]; - int len = 0; - FileOutputStream fos = null; - // 储存下载文件的目录 - File pathFile = new File(downloadApkPath); - if (!pathFile.exists()) { - pathFile.mkdirs(); - } - try { - is = response.body().byteStream(); - long total = response.body().contentLength(); - final File file = new File(downloadApkPath, fileName); - if (file.exists()) { - file.delete(); - } else { - file.createNewFile(); - } - fos = new FileOutputStream(file); - long sum = 0; - while ((len = is.read(buf)) != -1) { -// ALog.e("file total size:"+total); - fos.write(buf, 0, len); - sum += len; - final int progress = (int) (((double) sum / total) * 100); -// ALog.e("progress:" + progress); - // 下载中 - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (listener != null) - listener.onCheckerDownloading(progress); - } - }); - } - fos.flush(); - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (listener != null) - listener.onCheckerDownloadSuccess(file); - } - }); - - } catch (Exception e) { - handleFailed(listener); - - } finally { - try { - if (is != null) - is.close(); - if (fos != null) - fos.close(); - } catch (IOException e) { - handleFailed(listener); - - } - } - } else { - handleFailed(listener); - } - } - private static void handleFailed(final DownloadListener listener) { + private static void handleFailed(final DownloadListenerKt listener) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - if (listener != null) + if (listener != null && !listener.isDisposed()) listener.onCheckerDownloadFail(); } diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/net/RequestVersionManager.java b/library/src/main/java/com/allenliu/versionchecklib/v2/net/RequestVersionManager.java index d371df8..38598f3 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/net/RequestVersionManager.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/net/RequestVersionManager.java @@ -6,17 +6,13 @@ import com.allenliu.versionchecklib.core.http.AllenHttp; import com.allenliu.versionchecklib.core.http.HttpRequestMethod; +import com.allenliu.versionchecklib.utils.ALog; import com.allenliu.versionchecklib.v2.AllenVersionChecker; +import com.allenliu.versionchecklib.v2.builder.BuilderManager; import com.allenliu.versionchecklib.v2.builder.DownloadBuilder; import com.allenliu.versionchecklib.v2.builder.RequestVersionBuilder; import com.allenliu.versionchecklib.v2.builder.UIData; import com.allenliu.versionchecklib.v2.callback.RequestVersionListener; -import com.allenliu.versionchecklib.v2.eventbus.AllenEventType; -import com.allenliu.versionchecklib.v2.eventbus.CommonEvent; - -import org.greenrobot.eventbus.EventBus; -import org.greenrobot.eventbus.Subscribe; -import org.greenrobot.eventbus.ThreadMode; import java.io.IOException; import java.util.concurrent.Executors; @@ -32,8 +28,9 @@ * @since 1.0 */ public class RequestVersionManager { -// private boolean isCanceled=false; - private Handler handler = new Handler(Looper.getMainLooper()); + // private boolean isCanceled=false; + private final Handler handler = new Handler(Looper.getMainLooper()); + public static RequestVersionManager getInstance() { return Holder.instance; } @@ -42,24 +39,6 @@ public static class Holder { static RequestVersionManager instance = new RequestVersionManager(); } -// @Subscribe(threadMode = ThreadMode.MAIN) -// public void receiveEvent(CommonEvent commonEvent) { -// if(commonEvent.getEventType()== AllenEventType.CLOSE){ -// isCanceled=true; -// } -// } -// -// private void registerEventBus() { -// isCanceled=false; -// if(!EventBus.getDefault().isRegistered(this)) -// EventBus.getDefault().register(this); -// } -// private void unregister(){ -// -// if(EventBus.getDefault().isRegistered(this)) -// EventBus.getDefault().unregister(this); -// } - /** * 请求版本接口 * #issue 239 @@ -90,21 +69,20 @@ public void run() { final Response response = client.newCall(request).execute(); if (response.isSuccessful()) { final String result = response.body() != null ? response.body().string() : null; - post(new Runnable() { - @Override - public void run() { - - UIData versionBundle = requestVersionListener.onRequestVersionSuccess(builder, result); - if (versionBundle != null) { - builder.setVersionBundle(versionBundle); - builder.download(context); - } - } + post(new Runnable() { + @Override + public void run() { + UIData versionBundle = requestVersionListener.onRequestVersionSuccess(builder, result); + if (versionBundle != null) { + builder.setVersionBundle(versionBundle); + builder.download(context); + } + } - }); + }); } else { - post(new Runnable() { + post(new Runnable() { @Override public void run() { requestVersionListener.onRequestVersionFailure(response.message()); @@ -123,14 +101,16 @@ public void run() { }); } } else { - throw new RuntimeException("using request version function,you must set a requestVersionListener"); + ALog.e("using request version function,you must set a requestVersionListener"); + } // unregister(); } }); } - private void post(Runnable r){ + + private void post(Runnable r) { handler.post(r); } } diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.java deleted file mode 100644 index eb6f2c4..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; - -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; - -import android.view.View; -import android.view.ViewGroup; -import android.view.WindowManager; - -import com.allenliu.versionchecklib.v2.builder.BuilderManager; -import com.allenliu.versionchecklib.v2.builder.DownloadBuilder; -import com.allenliu.versionchecklib.v2.eventbus.AllenEventType; -import com.allenliu.versionchecklib.v2.eventbus.CommonEvent; - -import org.greenrobot.eventbus.EventBus; -import org.greenrobot.eventbus.Subscribe; -import org.greenrobot.eventbus.ThreadMode; - -/** - * Created by allenliu on 2018/1/18. - */ - -public abstract class AllenBaseActivity extends AppCompatActivity { - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (!EventBus.getDefault().isRegistered(this)) - EventBus.getDefault().register(this); - setTransparent(this); - } - - @Override - protected void onStop() { - - super.onStop(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - if (EventBus.getDefault().isRegistered(this)) - EventBus.getDefault().unregister(this); - } - - /** - * 使状态栏透明 - */ - @TargetApi(Build.VERSION_CODES.KITKAT) - private void transparentStatusBar(Activity activity) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); - activity.getWindow().setStatusBarColor(Color.TRANSPARENT); - } else { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - } - } - - /** - * 设置根布局参数 - */ - private void setRootView(Activity activity) { - ViewGroup parent = (ViewGroup) activity.findViewById(android.R.id.content); - for (int i = 0, count = parent.getChildCount(); i < count; i++) { - View childView = parent.getChildAt(i); - if (childView instanceof ViewGroup) { - childView.setFitsSystemWindows(true); - ((ViewGroup) childView).setClipToPadding(true); - } - } - } - - public void setTransparent(Activity activity) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { - return; - } - transparentStatusBar(activity); - setRootView(activity); - } - - protected void throwWrongIdsException() { - throw new RuntimeException("customize dialog must use the specify id that lib gives"); - } - - protected DownloadBuilder getVersionBuilder() { - if (BuilderManager.getInstance().getDownloadBuilder() == null) - finish(); - return BuilderManager.getInstance().getDownloadBuilder(); - - - } - - protected void checkForceUpdate() { - if (getVersionBuilder() != null && getVersionBuilder().getForceUpdateListener() != null) { - getVersionBuilder().getForceUpdateListener().onShouldForceUpdate(); - finish(); - } - } - - protected void cancelHandler() { - DownloadBuilder builder=getVersionBuilder(); - if (builder != null) { - if (builder.getOnCancelListener() != null) - builder.getOnCancelListener().onCancel(); - if(this instanceof UIActivity&&builder.getReadyDownloadCancelListener()!=null){ - builder.getReadyDownloadCancelListener().onCancel(); - }else if(this instanceof DownloadFailedActivity&&builder.getDownloadFailedCancelListener()!=null){ - builder.getDownloadFailedCancelListener().onCancel(); - }else if(this instanceof DownloadingActivity&&builder.getDownloadingCancelListener()!=null){ - builder.getDownloadingCancelListener().onCancel(); - } - } - } - - @Subscribe(threadMode = ThreadMode.MAIN) - public void receiveEvent(CommonEvent commonEvent) { - if (commonEvent.getEventType() == AllenEventType.CLOSE) { - finish(); - EventBus.getDefault().removeStickyEvent(commonEvent); - } - } - - public abstract void showDefaultDialog(); - - public abstract void showCustomDialog(); - - @Override - public void finish() { - super.finish(); - overridePendingTransition(0, 0); - } -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.kt new file mode 100644 index 0000000..7500c1d --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/AllenBaseActivity.kt @@ -0,0 +1,123 @@ +package com.allenliu.versionchecklib.v2.ui + +import android.R +import android.annotation.TargetApi +import android.app.Activity +import android.graphics.Color +import android.os.Build +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import android.view.WindowManager +import androidx.appcompat.app.AppCompatActivity +import com.allenliu.versionchecklib.v2.builder.BuilderManager.doWhenNotNull +import com.allenliu.versionchecklib.v2.eventbus.AllenEventType +import com.allenliu.versionchecklib.v2.eventbus.CommonEvent +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode + +/** + * Created by allenliu on 2018/1/18. + */ +abstract class AllenBaseActivity : AppCompatActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this) + setTransparent(this) + } + + override fun onStop() { + super.onStop() + } + + override fun onDestroy() { + super.onDestroy() + if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this) + } + + /** + * 使状态栏透明 + */ + @TargetApi(Build.VERSION_CODES.KITKAT) + private fun transparentStatusBar(activity: Activity) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + activity.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) + activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) + activity.window.statusBarColor = Color.TRANSPARENT + } else { + activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) + } + } + + /** + * 设置根布局参数 + */ + private fun setRootView(activity: Activity) { + val parent = activity.findViewById(R.id.content) as ViewGroup + var i = 0 + val count = parent.childCount + while (i < count) { + val childView = parent.getChildAt(i) + if (childView is ViewGroup) { + childView.setFitsSystemWindows(true) + childView.clipToPadding = true + } + i++ + } + } + + fun setTransparent(activity: Activity) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { + return + } + transparentStatusBar(activity) + setRootView(activity) + } + + protected fun throwWrongIdsException() { + throw RuntimeException("customize dialog must use the specify id that lib gives") + } + + protected fun checkForceUpdate() { + doWhenNotNull { + if (forceUpdateListener != null) { + forceUpdateListener?.onShouldForceUpdate() + finish() + } + } + } + + protected fun cancelHandler() { + doWhenNotNull { + onCancelListener?.onCancel() + if (this@AllenBaseActivity is UIActivity && readyDownloadCancelListener != null) { + readyDownloadCancelListener?.onCancel() + } else if (this@AllenBaseActivity is DownloadFailedActivity && downloadFailedCancelListener != null) { + downloadFailedCancelListener?.onCancel() + } else if (this@AllenBaseActivity is DownloadingActivity && downloadingCancelListener != null) { + downloadingCancelListener?.onCancel() + } else { + null + } + } + } + + @Subscribe(threadMode = ThreadMode.MAIN) + open fun receiveEvent(commonEvent: CommonEvent<*>) { + if (commonEvent.eventType == AllenEventType.CLOSE) { + finish() + EventBus.getDefault().removeStickyEvent(commonEvent) + } + } + + abstract fun showDefaultDialog() + abstract fun showCustomDialog() + override fun finish() { + super.finish() + overridePendingTransition(0, 0) + } +} + + diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/BuilderHelper.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/BuilderHelper.java deleted file mode 100644 index 199decf..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/BuilderHelper.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.content.Context; -import android.content.Intent; - -import com.allenliu.versionchecklib.R; -import com.allenliu.versionchecklib.core.DownloadManager; -import com.allenliu.versionchecklib.utils.ALog; -import com.allenliu.versionchecklib.v2.AllenVersionChecker; -import com.allenliu.versionchecklib.v2.builder.DownloadBuilder; - -import java.io.File; - -/** - * Created by allenliu on 2018/1/18. - */ - -public class BuilderHelper { - private DownloadBuilder builder; - private Context context; - - public BuilderHelper(Context context, DownloadBuilder builder) { - this.context = context; - this.builder = builder; - } - - /** - * 验证安装包是否存在,并且在安装成功情况下删除安装包 - */ - public void checkAndDeleteAPK() { - //判断versioncode与当前版本不一样的apk是否存在,存在删除安装包 - try { - String downloadPath = builder.getDownloadAPKPath() + context.getString(R.string.versionchecklib_download_apkname, context.getPackageName()); - if (!DownloadManager.checkAPKIsExists(context, downloadPath)) { - ALog.e("删除本地apk"); - new File(downloadPath).delete(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void checkForceUpdate() { - if (builder.getForceUpdateListener() != null) { - builder.getForceUpdateListener().onShouldForceUpdate(); - AllenVersionChecker.getInstance().cancelAllMission(); - } - } -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.java deleted file mode 100644 index f02f526..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.app.Dialog; -import android.content.DialogInterface; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; -import android.os.Bundle; -import android.view.View; - -import com.allenliu.versionchecklib.R; -import com.allenliu.versionchecklib.utils.ALog; -import com.allenliu.versionchecklib.utils.AllenEventBusUtil; -import com.allenliu.versionchecklib.v2.AllenVersionChecker; -import com.allenliu.versionchecklib.v2.eventbus.AllenEventType; - -public class DownloadFailedActivity extends AllenBaseActivity implements DialogInterface.OnCancelListener { - private Dialog downloadFailedDialog; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - showDowloadFailedDialog(); - } - - @Override - public void showDefaultDialog() { - downloadFailedDialog = new AlertDialog.Builder(this).setMessage(getString(R.string.versionchecklib_download_fail_retry)).setPositiveButton(getString(R.string.versionchecklib_confirm), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - retryDownload(); - } - }).setNegativeButton(getString(R.string.versionchecklib_cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - onCancel(downloadFailedDialog); - } - }).create(); - downloadFailedDialog.setCanceledOnTouchOutside(false); - downloadFailedDialog.setCancelable(true); - downloadFailedDialog.show(); - } - - @Override - public void showCustomDialog() { - if(getVersionBuilder()!=null) { - downloadFailedDialog = getVersionBuilder().getCustomDownloadFailedListener().getCustomDownloadFailed(this, getVersionBuilder().getVersionBundle()); - View retryView = downloadFailedDialog.findViewById(R.id.versionchecklib_failed_dialog_retry); - if (retryView != null) { - retryView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - retryDownload(); - } - }); - } - View cancelView = downloadFailedDialog.findViewById(R.id.versionchecklib_failed_dialog_cancel); - if (cancelView != null) { - cancelView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - onCancel(downloadFailedDialog); - } - }); - } - downloadFailedDialog.show(); - } - } - - private void showDowloadFailedDialog() { - AllenEventBusUtil.sendEventBusStick(AllenEventType.CLOSE_DOWNLOADING_ACTIVITY); - - if (getVersionBuilder()!=null&&getVersionBuilder().getCustomDownloadFailedListener() != null) { - ALog.e("show customization failed dialog"); - showCustomDialog(); - } else { - ALog.e("show default failed dialog"); - showDefaultDialog(); - } - downloadFailedDialog.setOnCancelListener(this); - } - - @Override - public void onCancel(DialogInterface dialogInterface) { - ALog.e("on cancel" + - ""); - cancelHandler(); - checkForceUpdate(); - AllenVersionChecker.getInstance().cancelAllMission(); - finish(); - } - - private void retryDownload() { - //增加commit 回调 - if(getVersionBuilder().getDownloadFailedCommitClickListener()!=null){ - getVersionBuilder().getDownloadFailedCommitClickListener().onCommitClick(); - } - AllenEventBusUtil.sendEventBus(AllenEventType.START_DOWNLOAD_APK); - finish(); - } - - @Override - protected void onPause() { - super.onPause(); - if(downloadFailedDialog!=null&&downloadFailedDialog.isShowing()) - downloadFailedDialog.dismiss(); -// finish(); - } - - @Override - protected void onResume() { - super.onResume(); - if(downloadFailedDialog!=null&&!downloadFailedDialog.isShowing()) - downloadFailedDialog.show(); - } -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.kt new file mode 100644 index 0000000..933a7fd --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadFailedActivity.kt @@ -0,0 +1,93 @@ +package com.allenliu.versionchecklib.v2.ui + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import android.view.View +import androidx.appcompat.app.AlertDialog +import com.allenliu.versionchecklib.R +import com.allenliu.versionchecklib.utils.ALog +import com.allenliu.versionchecklib.utils.AllenEventBusUtil +import com.allenliu.versionchecklib.v2.AllenVersionChecker +import com.allenliu.versionchecklib.v2.builder.BuilderManager +import com.allenliu.versionchecklib.v2.eventbus.AllenEventType + +class DownloadFailedActivity : AllenBaseActivity(), DialogInterface.OnCancelListener { + private var downloadFailedDialog: Dialog? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + showDowloadFailedDialog() + } + + override fun showDefaultDialog() { + downloadFailedDialog = AlertDialog + .Builder(this) + .setMessage(getString(R.string.versionchecklib_download_fail_retry)) + .setPositiveButton(getString(R.string.versionchecklib_confirm)) { _, _ -> retryDownload() } + .setNegativeButton(getString(R.string.versionchecklib_cancel)) { d, _ -> onCancel(d) } + .create().apply { + setCanceledOnTouchOutside(false) + setCancelable(true) + show() + } + + } + + override fun showCustomDialog() { + BuilderManager.doWhenNotNull { + downloadFailedDialog = customDownloadFailedListener.getCustomDownloadFailed(this@DownloadFailedActivity, versionBundle).apply { + val retryView = findViewById(R.id.versionchecklib_failed_dialog_retry) + retryView?.setOnClickListener { retryDownload() } + val cancelView = findViewById(R.id.versionchecklib_failed_dialog_cancel) + cancelView?.setOnClickListener { onCancel(this) } + show() + + } + + } + } + + private fun showDowloadFailedDialog() { + AllenEventBusUtil.sendEventBusStick(AllenEventType.CLOSE_DOWNLOADING_ACTIVITY) + BuilderManager.doWhenNotNull { + if (customDownloadFailedListener != null) { + ALog.e("show customization failed dialog") + showCustomDialog() + } else { + ALog.e("show default failed dialog") + showDefaultDialog() + } + downloadFailedDialog?.setOnCancelListener(this@DownloadFailedActivity) + } + + } + + override fun onCancel(dialogInterface: DialogInterface) { + ALog.e("on cancel" + + "") + cancelHandler() + checkForceUpdate() + AllenVersionChecker.getInstance().cancelAllMission() + finish() + } + + private fun retryDownload() { + //增加commit 回调 + BuilderManager.doWhenNotNull { + downloadFailedCommitClickListener?.onCommitClick() + } + AllenEventBusUtil.sendEventBus(AllenEventType.START_DOWNLOAD_APK) + finish() + } + + override fun onPause() { + super.onPause() + if (downloadFailedDialog != null && downloadFailedDialog!!.isShowing) downloadFailedDialog!!.dismiss() + // finish(); + } + + override fun onResume() { + super.onResume() + if (downloadFailedDialog != null && !downloadFailedDialog!!.isShowing) downloadFailedDialog!!.show() + } +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.java deleted file mode 100644 index 3d1a19a..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.app.Dialog; -import android.content.DialogInterface; - -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.ProgressBar; -import android.widget.TextView; - -import com.allenliu.versionchecklib.R; -import com.allenliu.versionchecklib.core.http.AllenHttp; -import com.allenliu.versionchecklib.utils.ALog; -import com.allenliu.versionchecklib.v2.eventbus.AllenEventType; -import com.allenliu.versionchecklib.v2.eventbus.CommonEvent; - -import org.greenrobot.eventbus.EventBus; - -public class DownloadingActivity extends AllenBaseActivity implements DialogInterface.OnCancelListener { - public static final String PROGRESS = "progress"; - private Dialog downloadingDialog; - private int currentProgress = 0; - protected boolean isDestroy = false; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ALog.e("loading activity create"); - - showLoadingDialog(); - } - - public void onCancel(boolean isDownloadCompleted) { - if (!isDownloadCompleted) { - AllenHttp.getHttpClient().dispatcher().cancelAll(); - cancelHandler(); - checkForceUpdate(); - } - finish(); - } - - @Override - public void onCancel(DialogInterface dialog) { - onCancel(false); - } - - - @Override - public void receiveEvent(CommonEvent commonEvent) { - super.receiveEvent(commonEvent); - switch (commonEvent.getEventType()) { - case AllenEventType.UPDATE_DOWNLOADING_PROGRESS: - int progress = (int) commonEvent.getData(); - currentProgress = progress; - updateProgress(); - break; - case AllenEventType.DOWNLOAD_COMPLETE: - onCancel(true); - break; - case AllenEventType.CLOSE_DOWNLOADING_ACTIVITY: - destroy(); - EventBus.getDefault().removeStickyEvent(commonEvent); - break; - } - } - - @Override - public void showDefaultDialog() { - View loadingView = LayoutInflater.from(this).inflate(R.layout.downloading_layout, null); - downloadingDialog = new AlertDialog.Builder(this).setTitle("").setView(loadingView).create(); - if (getVersionBuilder().getForceUpdateListener() != null) - downloadingDialog.setCancelable(false); - else - downloadingDialog.setCancelable(true); - - downloadingDialog.setCanceledOnTouchOutside(false); - ProgressBar pb = loadingView.findViewById(R.id.pb); - TextView tvProgress = loadingView.findViewById(R.id.tv_progress); - tvProgress.setText(String.format(getString(R.string.versionchecklib_progress), currentProgress)); - pb.setProgress(currentProgress); - downloadingDialog.show(); - } - - @Override - public void showCustomDialog() { - if(getVersionBuilder()!=null) { - downloadingDialog = getVersionBuilder().getCustomDownloadingDialogListener().getCustomDownloadingDialog(this, currentProgress, getVersionBuilder().getVersionBundle()); - if (getVersionBuilder().getForceUpdateListener() != null) - downloadingDialog.setCancelable(false); - else - downloadingDialog.setCancelable(true); - View cancelView = downloadingDialog.findViewById(R.id.versionchecklib_loading_dialog_cancel); - if (cancelView != null) { - cancelView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - onCancel(false); - } - }); - } - downloadingDialog.show(); - } - } - - @Override - protected void onPause() { - super.onPause(); - destroyWithOutDismiss(); - isDestroy = true; - } - - @Override - protected void onResume() { - super.onResume(); - isDestroy = false; - if (downloadingDialog != null && !downloadingDialog.isShowing()) - downloadingDialog.show(); - } - - private void destroyWithOutDismiss() { - if (downloadingDialog != null && downloadingDialog.isShowing()) { - downloadingDialog.dismiss(); -// onCancel(false); - } - } - - private void destroy() { - ALog.e("loading activity destroy"); - if (downloadingDialog != null && downloadingDialog.isShowing()) { - downloadingDialog.dismiss(); -// onCancel(false); - } - finish(); - } - - private void updateProgress() { - if (!isDestroy) { - if (getVersionBuilder() != null && getVersionBuilder().getCustomDownloadingDialogListener() != null) { - getVersionBuilder().getCustomDownloadingDialogListener().updateUI(downloadingDialog, currentProgress, getVersionBuilder().getVersionBundle()); - } else { - ProgressBar pb = downloadingDialog.findViewById(R.id.pb); - pb.setProgress(currentProgress); - TextView tvProgress = downloadingDialog.findViewById(R.id.tv_progress); - tvProgress.setText(String.format(getString(R.string.versionchecklib_progress), currentProgress)); - if (!downloadingDialog.isShowing()) - downloadingDialog.show(); - } - } - } - - private void showLoadingDialog() { - ALog.e("show loading"); - if (!isDestroy) { - if (getVersionBuilder() != null && getVersionBuilder().getCustomDownloadingDialogListener() != null) { - showCustomDialog(); - } else { - showDefaultDialog(); - } - downloadingDialog.setOnCancelListener(this); - } - } - - -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.kt new file mode 100644 index 0000000..adb623d --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/DownloadingActivity.kt @@ -0,0 +1,153 @@ +package com.allenliu.versionchecklib.v2.ui + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.widget.ProgressBar +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import com.allenliu.versionchecklib.R +import com.allenliu.versionchecklib.core.http.AllenHttp +import com.allenliu.versionchecklib.utils.ALog +import com.allenliu.versionchecklib.v2.builder.BuilderManager +import com.allenliu.versionchecklib.v2.eventbus.AllenEventType +import com.allenliu.versionchecklib.v2.eventbus.CommonEvent +import org.greenrobot.eventbus.EventBus + +class DownloadingActivity : AllenBaseActivity(), DialogInterface.OnCancelListener { + private var downloadingDialog: Dialog? = null + private var currentProgress = 0 + protected var isDestroy = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ALog.e("loading activity create") + showLoadingDialog() + } + + fun onCancel(isDownloadCompleted: Boolean) { + if (!isDownloadCompleted) { + AllenHttp.getHttpClient().dispatcher.cancelAll() + cancelHandler() + checkForceUpdate() + } + finish() + } + + override fun onCancel(dialog: DialogInterface) { + onCancel(false) + } + + override fun receiveEvent(commonEvent: CommonEvent<*>) { + super.receiveEvent(commonEvent) + when (commonEvent.eventType) { + AllenEventType.UPDATE_DOWNLOADING_PROGRESS -> { + val progress = commonEvent.data as Int + currentProgress = progress + updateProgress() + } + AllenEventType.DOWNLOAD_COMPLETE -> onCancel(true) + AllenEventType.CLOSE_DOWNLOADING_ACTIVITY -> { + destroy() + EventBus.getDefault().removeStickyEvent(commonEvent) + } + } + } + + override fun showDefaultDialog() { + val loadingView = LayoutInflater.from(this).inflate(R.layout.downloading_layout, null) + downloadingDialog = AlertDialog.Builder(this).setTitle("").setView(loadingView).create().apply { + BuilderManager.doWhenNotNull { + if (forceUpdateListener != null) setCancelable(false) else setCancelable(true) + setCanceledOnTouchOutside(false) + val pb = loadingView.findViewById(R.id.pb) + val tvProgress = loadingView.findViewById(R.id.tv_progress) + tvProgress.text = String.format(getString(R.string.versionchecklib_progress), currentProgress) + pb.progress = currentProgress + show() + } + + } + + } + + override fun showCustomDialog() { + BuilderManager.doWhenNotNull { + downloadingDialog = customDownloadingDialogListener.getCustomDownloadingDialog(this@DownloadingActivity, currentProgress, versionBundle).apply { + if (forceUpdateListener != null) setCancelable(false) else setCancelable(true) + val cancelView = findViewById(R.id.versionchecklib_loading_dialog_cancel) + cancelView?.setOnClickListener { onCancel(false) } + show() + } + } + + + } + + override fun onPause() { + super.onPause() + destroyWithOutDismiss() + isDestroy = true + } + + override fun onResume() { + super.onResume() + isDestroy = false + downloadingDialog?.let { + if (!it.isShowing) { + it.show() + } + } + + } + + private fun destroyWithOutDismiss() { + downloadingDialog?.let { + if (it.isShowing) { + it.dismiss() + } + } + } + + private fun destroy() { + ALog.e("loading activity destroy") + destroyWithOutDismiss() + finish() + } + + private fun updateProgress() { + if (!isDestroy) { + BuilderManager.doWhenNotNull { + if (customDownloadingDialogListener != null) { + customDownloadingDialogListener.updateUI(downloadingDialog, currentProgress, versionBundle) + } else { + val pb = downloadingDialog?.findViewById(R.id.pb) + pb?.progress = currentProgress + val tvProgress = downloadingDialog?.findViewById(R.id.tv_progress) + tvProgress?.text = String.format(getString(R.string.versionchecklib_progress), currentProgress) + downloadingDialog?.show() + } + } + + } + } + + private fun showLoadingDialog() { + ALog.e("show loading") + if (!isDestroy) { + BuilderManager.doWhenNotNull { + if (customDownloadingDialogListener != null) { + showCustomDialog() + } else { + showDefaultDialog() + } + } + downloadingDialog?.setOnCancelListener(this) + } + } + + companion object { + const val PROGRESS = "progress" + } +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.java deleted file mode 100644 index 9047a31..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.media.Ringtone; -import android.media.RingtoneManager; -import android.net.Uri; -import android.os.Build; - -import androidx.annotation.RequiresApi; -import androidx.core.app.NotificationCompat; - -import com.allenliu.versionchecklib.R; -import com.allenliu.versionchecklib.core.PermissionDialogActivity; -import com.allenliu.versionchecklib.core.VersionFileProvider; -import com.allenliu.versionchecklib.utils.ALog; -import com.allenliu.versionchecklib.v2.builder.DownloadBuilder; -import com.allenliu.versionchecklib.v2.builder.NotificationBuilder; - -import java.io.File; - -import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; -import static android.content.Context.NOTIFICATION_SERVICE; - -/** - * Created by allenliu on 2018/1/19. - */ - -public class NotificationHelper { - private DownloadBuilder versionBuilder; - private Context context; - NotificationCompat.Builder notificationBuilder = null; - NotificationManager manager = null; - private boolean isDownloadSuccess = false, isFailed = false; - private int currentProgress = 0; - private String contentText; - public static final int NOTIFICATION_ID = 1; - - public NotificationHelper(Context context, DownloadBuilder builder) { - this.context = context; - this.versionBuilder = builder; - currentProgress = 0; - } - - /** - * update notification progress - * - * @param progress the progress of notification - */ - public void updateNotification(int progress) { - if (versionBuilder.isShowNotification()) { - if ((progress - currentProgress) > 5 && !isDownloadSuccess && !isFailed) { - notificationBuilder.setContentIntent(null); - notificationBuilder.setContentText(String.format(contentText, progress)); - notificationBuilder.setProgress(100, progress, false); - manager.notify(NOTIFICATION_ID, notificationBuilder.build()); - currentProgress = progress; - } - } - } - - /** - * show notification - */ - public void showNotification() { - isDownloadSuccess = false; - isFailed = false; - if (versionBuilder.isShowNotification()) { - manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); - notificationBuilder = createNotification(); - manager.notify(NOTIFICATION_ID, notificationBuilder.build()); - } - } - - /** - * show download success notification - */ - public void showDownloadCompleteNotifcation(File file) { - isDownloadSuccess = true; - if (!versionBuilder.isShowNotification()) - return; - Intent i = new Intent(Intent.ACTION_VIEW); - Uri uri; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - uri = VersionFileProvider.getUriForFile(context, context.getPackageName() + ".versionProvider", file); - ALog.e(context.getPackageName() + ""); - i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - } else { - uri = Uri.fromFile(file); - } - //设置intent的类型 - i.setDataAndType(uri, - "application/vnd.android.package-archive"); - PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0); - notificationBuilder.setContentIntent(pendingIntent); - notificationBuilder.setContentText(context.getString(R.string.versionchecklib_download_finish)); - notificationBuilder.setProgress(100, 100, false); - manager.cancelAll(); - manager.notify(NOTIFICATION_ID, notificationBuilder.build()); - } - - public void showDownloadFailedNotification() { - isDownloadSuccess = false; - isFailed = true; - if (versionBuilder.isShowNotification()) { - Intent intent = new Intent(context, PermissionDialogActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, FLAG_UPDATE_CURRENT); - notificationBuilder.setContentIntent(pendingIntent); - notificationBuilder.setContentText(context.getString(R.string.versionchecklib_download_fail)); - notificationBuilder.setProgress(100, 0, false); - manager.notify(NOTIFICATION_ID, notificationBuilder.build()); - } - } - - private NotificationCompat.Builder createNotification() { - final String CHANNEL_ID = "0", CHANNEL_NAME = "ALLEN_NOTIFICATION"; - NotificationCompat.Builder builder = null; - NotificationBuilder libNotificationBuilder = versionBuilder.getNotificationBuilder(); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { - NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW); - notificationChannel.enableLights(false); - notificationChannel.setLightColor(Color.RED); - notificationChannel.enableVibration(false); - NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); - manager.createNotificationChannel(notificationChannel); - } - builder = new NotificationCompat.Builder(context, CHANNEL_ID); - builder.setAutoCancel(true); - builder.setSmallIcon(versionBuilder.getNotificationBuilder().getIcon()); - //set content title - String contentTitle = context.getString(R.string.app_name); - if (libNotificationBuilder.getContentTitle() != null) - contentTitle = libNotificationBuilder.getContentTitle(); - builder.setContentTitle(contentTitle); - //set ticker - String ticker = context.getString(R.string.versionchecklib_downloading); - if (libNotificationBuilder.getTicker() != null) - ticker = libNotificationBuilder.getTicker(); - builder.setTicker(ticker); - //set content text - contentText = context.getString(R.string.versionchecklib_download_progress); - if (libNotificationBuilder.getContentText() != null) - contentText = libNotificationBuilder.getContentText(); - builder.setContentText(String.format(contentText, 0)); - - if (libNotificationBuilder.isRingtone()) { - Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); - Ringtone r = RingtoneManager.getRingtone(context, notification); - if (r != null) - r.play(); - } - - return builder; - } - - public void onDestroy() { - if (manager != null) - manager.cancel(NOTIFICATION_ID); - } - - private static final String channelid = "version_service_id"; - - public Notification getServiceNotification() { - - NotificationCompat.Builder notifcationBuilder = new NotificationCompat.Builder(context, channelid) - .setContentTitle(context.getString(R.string.app_name)) - .setContentText(context.getString(R.string.versionchecklib_version_service_runing)) - .setSmallIcon(versionBuilder.getNotificationBuilder().getIcon()) - .setAutoCancel(false); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { - NotificationChannel notificationChannel = new NotificationChannel(channelid, "version_service_name", NotificationManager.IMPORTANCE_LOW); - notificationChannel.enableLights(false); -// notificationChannel.setLightColor(getColor(R.color.versionchecklib_theme_color)); - notificationChannel.enableVibration(false); - NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - if (manager != null) { - manager.createNotificationChannel(notificationChannel); - } - - } - return notifcationBuilder.build(); - - } - - @RequiresApi(api = Build.VERSION_CODES.O) - public static Notification createSimpleNotification(Context context) { - NotificationChannel channel = new NotificationChannel(channelid, - "MyApp", NotificationManager.IMPORTANCE_DEFAULT); - ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel); - return new NotificationCompat.Builder(context, channelid) - .setContentTitle("") - .setContentText("").build(); - } -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.kt new file mode 100644 index 0000000..5cb6e9f --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/NotificationHelper.kt @@ -0,0 +1,207 @@ +package com.allenliu.versionchecklib.v2.ui + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.graphics.Color +import android.media.RingtoneManager +import android.net.Uri +import android.os.Build +import androidx.annotation.RequiresApi +import androidx.core.app.NotificationCompat +import com.allenliu.versionchecklib.R +import com.allenliu.versionchecklib.core.PermissionDialogActivity +import com.allenliu.versionchecklib.core.VersionFileProvider +import com.allenliu.versionchecklib.utils.ALog +import com.allenliu.versionchecklib.v2.builder.BuilderManager +import com.allenliu.versionchecklib.v2.builder.DownloadBuilder +import com.allenliu.versionchecklib.v2.builder.NotificationBuilder +import java.io.File + +/** + * Created by allenliu on 2018/1/19. + */ +class NotificationHelper(private val context: Context) { + var notification: NotificationCompat.Builder? = null + private val manager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + private var isDownloadSuccess = false + private var isFailed = false + private var currentProgress = 0 + private var contentText: String? = null + + /** + * update notification progress + * + * @param progress the progress of notification + */ + fun updateNotification(progress: Int) { + BuilderManager.doWhenNotNull { + if (isShowNotification) { + notification?.let { + if (progress - currentProgress > 5 && !isDownloadSuccess && !isFailed) { + contentText?.let { text -> + it.setContentIntent(null) + it.setContentText(String.format(text, progress)) + it.setProgress(100, progress, false) + manager.notify(NOTIFICATION_ID, it.build()) + currentProgress = progress + } + + + } + } + + } + } + + } + + /** + * show notification + */ + fun showNotification() { + isDownloadSuccess = false + isFailed = false + BuilderManager.doWhenNotNull { + if (isShowNotification) { + notification = createNotification(this) + manager.notify(NOTIFICATION_ID, notification?.build()) + } + } + + } + + /** + * show download success notification + */ + fun showDownloadCompleteNotifcation(file: File) { + BuilderManager.doWhenNotNull { + isDownloadSuccess = true + if (!isShowNotification) return@doWhenNotNull + val i = Intent(Intent.ACTION_VIEW) + val uri: Uri + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + uri = VersionFileProvider.getUriForFile(context, context.packageName + ".versionProvider", file) + ALog.e(context.packageName + "") + i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } else { + uri = Uri.fromFile(file) + } + //设置intent的类型 + i.setDataAndType(uri, + "application/vnd.android.package-archive") + val pendingIntent = PendingIntent.getActivity(context, 0, i, 0) + notification?.let { + it.setContentIntent(pendingIntent) + it.setContentText(context.getString(R.string.versionchecklib_download_finish)) + it.setProgress(100, 100, false) + manager.cancelAll() + manager.notify(NOTIFICATION_ID, it.build()) + } + + } + + } + + fun showDownloadFailedNotification() { + isDownloadSuccess = false + isFailed = true + BuilderManager.doWhenNotNull { + if (isShowNotification) { + notification?.let { + val intent = Intent(context, PermissionDialogActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) + it.setContentIntent(pendingIntent) + it.setContentText(context.getString(R.string.versionchecklib_download_fail)) + it.setProgress(100, 0, false) + manager.notify(NOTIFICATION_ID, it.build()) + } + + } + } + + } + + private fun createNotification(versionBuilder: DownloadBuilder): NotificationCompat.Builder { + val CHANNEL_ID = "0" + val CHANNEL_NAME = "ALLEN_NOTIFICATION" + val builder: NotificationCompat.Builder? + val libNotificationBuilder: NotificationBuilder = versionBuilder.notificationBuilder + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val notificationChannel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW) + notificationChannel.enableLights(false) + notificationChannel.lightColor = Color.RED + notificationChannel.enableVibration(false) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.createNotificationChannel(notificationChannel) + } + builder = NotificationCompat.Builder(context, CHANNEL_ID) + builder.setAutoCancel(true) + builder.setSmallIcon(versionBuilder.notificationBuilder.icon) + //set content title + var contentTitle: String? = context.getString(R.string.app_name) + if (libNotificationBuilder.contentTitle != null) contentTitle = libNotificationBuilder.contentTitle + builder.setContentTitle(contentTitle) + //set ticker + var ticker: String? = context.getString(R.string.versionchecklib_downloading) + if (libNotificationBuilder.ticker != null) ticker = libNotificationBuilder.ticker + builder.setTicker(ticker) + //set content text + contentText = context.getString(R.string.versionchecklib_download_progress) + if (libNotificationBuilder.contentText != null) contentText = libNotificationBuilder.contentText + builder.setContentText(String.format(contentText!!, 0)) + if (libNotificationBuilder.isRingtone) { + val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) + val r = RingtoneManager.getRingtone(context, notification) + r?.play() + } + return builder + } + + fun onDestroy() { + manager.cancel(NOTIFICATION_ID) + } + + // notificationChannel.setLightColor(getColor(R.color.versionchecklib_theme_color)); + val serviceNotification: Notification + get() { + val notifcationBuilder = NotificationCompat.Builder(context, channelid) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(context.getString(R.string.versionchecklib_version_service_runing)) + .setAutoCancel(false) + + BuilderManager.getDownloadBuilder()?.notificationBuilder?.icon?.let { notifcationBuilder.setSmallIcon(it) } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val notificationChannel = NotificationChannel(channelid, "version_service_name", NotificationManager.IMPORTANCE_LOW) + notificationChannel.enableLights(false) + notificationChannel.enableVibration(false) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.createNotificationChannel(notificationChannel) + } + return notifcationBuilder.build() + } + + companion object { + const val NOTIFICATION_ID = 1 + private const val channelid = "version_service_id" + + @RequiresApi(api = Build.VERSION_CODES.O) + fun createSimpleNotification(context: Context): Notification { + val channel = NotificationChannel(channelid, + "MyApp", NotificationManager.IMPORTANCE_DEFAULT) + (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel) + return NotificationCompat.Builder(context, channelid) + .setContentTitle("") + .setContentText("").build() + } + } + + init { + currentProgress = 0 + } +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.java deleted file mode 100644 index 2c32368..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.app.Dialog; -import android.content.DialogInterface; -import android.os.Bundle; -import androidx.appcompat.app.AlertDialog; -import android.view.View; - -import com.allenliu.versionchecklib.R; -import com.allenliu.versionchecklib.utils.ALog; -import com.allenliu.versionchecklib.utils.AllenEventBusUtil; -import com.allenliu.versionchecklib.utils.AppUtils; -import com.allenliu.versionchecklib.v2.AllenVersionChecker; -import com.allenliu.versionchecklib.v2.builder.DownloadBuilder; -import com.allenliu.versionchecklib.v2.builder.UIData; -import com.allenliu.versionchecklib.v2.eventbus.AllenEventType; - -import java.io.File; - -public class UIActivity extends AllenBaseActivity implements DialogInterface.OnCancelListener { - private Dialog versionDialog; - private boolean isDestroy = false; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ALog.e("version activity create"); - - showVersionDialog(); - - } - - @Override - protected void onDestroy() { - isDestroy = true; - ALog.e("version activity destroy"); - super.onDestroy(); - } - -// @Override -// public void receiveEvent(CommonEvent commonEvent) { -// switch (commonEvent.getEventType()) { -// case AllenEventType.SHOW_VERSION_DIALOG: -// showVersionDialog(); -// break; -// } -// -// } - - @Override - public void showDefaultDialog() { - if (getVersionBuilder() != null) { - UIData uiData = getVersionBuilder().getVersionBundle(); - String title = "提示", content = "检测到新版本"; - if (uiData != null) { - title = uiData.getTitle(); - content = uiData.getContent(); - } - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this).setTitle(title).setMessage(content).setPositiveButton(getString(R.string.versionchecklib_confirm), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dealVersionDialogCommit(); - - } - }); - if (getVersionBuilder().getForceUpdateListener() == null) { - alertBuilder.setNegativeButton(getString(R.string.versionchecklib_cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - onCancel(versionDialog); - } - }); - alertBuilder.setCancelable(false); - - - } else { - alertBuilder.setCancelable(false); - } - versionDialog = alertBuilder.create(); - versionDialog.setCanceledOnTouchOutside(false); - versionDialog.show(); - } - } - - @Override - public void showCustomDialog() { - if (getVersionBuilder() != null) { - ALog.e("show customization dialog"); - versionDialog = getVersionBuilder().getCustomVersionDialogListener().getCustomVersionDialog(this, getVersionBuilder().getVersionBundle()); - try { - //自定义dialog,commit button 必须存在 - final View view = versionDialog.findViewById(R.id.versionchecklib_version_dialog_commit); - if (view != null) { - ALog.e("view not null"); - - view.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - ALog.e("click"); - dealVersionDialogCommit(); - } - }); - - } else { - throwWrongIdsException(); - } - //如果有取消按钮,id也必须对应 - View cancelView = versionDialog.findViewById(R.id.versionchecklib_version_dialog_cancel); - if (cancelView != null) { - cancelView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - onCancel(versionDialog); - } - }); - } - } catch (Exception e) { - e.printStackTrace(); - throwWrongIdsException(); - } - versionDialog.show(); - } - } - - private void showVersionDialog() { - if (getVersionBuilder() != null && getVersionBuilder().getCustomVersionDialogListener() != null) { - showCustomDialog(); - } else { - showDefaultDialog(); - } - if (versionDialog != null) { - versionDialog.setOnCancelListener(this); - } - } - - @Override - protected void onPause() { - super.onPause(); - if (versionDialog != null && versionDialog.isShowing()) - versionDialog.dismiss(); - } - - @Override - protected void onResume() { - super.onResume(); - if (versionDialog != null && !versionDialog.isShowing()) - versionDialog.show(); - } - - private void dealVersionDialogCommit() { - DownloadBuilder versionBuilder = getVersionBuilder(); - if (versionBuilder != null) { - //增加commit 回调 - if(versionBuilder.getReadyDownloadCommitClickListener()!=null){ - versionBuilder.getReadyDownloadCommitClickListener().onCommitClick(); - } - //如果是静默下载直接安装 - if (versionBuilder.isSilentDownload()) { - String downloadPath = versionBuilder.getDownloadAPKPath() + getString(R.string.versionchecklib_download_apkname, versionBuilder.getApkName() != null ? versionBuilder.getApkName() : getPackageName()); - AppUtils.installApk(this, new File(downloadPath), versionBuilder.getCustomInstallListener()); - checkForceUpdate(); - //否定开始下载 - } else { - AllenEventBusUtil.sendEventBus(AllenEventType.START_DOWNLOAD_APK); - } - finish(); - } - } - - - @Override - public void onCancel(DialogInterface dialogInterface) { - cancelHandler(); - checkForceUpdate(); - AllenVersionChecker.getInstance().cancelAllMission(); - finish(); - } - -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.kt new file mode 100644 index 0000000..88a6fcd --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/UIActivity.kt @@ -0,0 +1,146 @@ +package com.allenliu.versionchecklib.v2.ui + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import android.view.View +import androidx.appcompat.app.AlertDialog +import com.allenliu.versionchecklib.R +import com.allenliu.versionchecklib.utils.ALog +import com.allenliu.versionchecklib.utils.AllenEventBusUtil +import com.allenliu.versionchecklib.utils.AppUtils +import com.allenliu.versionchecklib.v2.AllenVersionChecker +import com.allenliu.versionchecklib.v2.builder.BuilderManager +import com.allenliu.versionchecklib.v2.builder.DownloadBuilder +import com.allenliu.versionchecklib.v2.builder.UIData +import com.allenliu.versionchecklib.v2.eventbus.AllenEventType +import java.io.File + +class UIActivity : AllenBaseActivity(), DialogInterface.OnCancelListener { + private var versionDialog: Dialog? = null + private var isDestroy = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + ALog.e("version activity create") + showVersionDialog() + } + + override fun onDestroy() { + isDestroy = true + ALog.e("version activity destroy") + super.onDestroy() + } + + override fun showDefaultDialog() { + val builder = BuilderManager.getDownloadBuilder() + if (builder != null) { + val uiData: UIData? = builder.versionBundle + var title: String? = "提示" + var content: String = "检测到新版本" + if (uiData != null) { + title = uiData.title + content = uiData.content + } + val alertBuilder = AlertDialog.Builder(this).setTitle(title).setMessage(content).setPositiveButton(getString(R.string.versionchecklib_confirm)) { _, _ -> dealVersionDialogCommit() } + if (builder.forceUpdateListener == null) { + alertBuilder.setNegativeButton(getString(R.string.versionchecklib_cancel)) { d, _ -> onCancel(d) } + alertBuilder.setCancelable(false) + } else { + alertBuilder.setCancelable(false) + } + versionDialog = alertBuilder.create().apply { + setCanceledOnTouchOutside(false) + show() + } + + } + } + + override fun showCustomDialog() { + val builder = BuilderManager.getDownloadBuilder() ?: return + ALog.e("show customization dialog") + versionDialog = builder.customVersionDialogListener.getCustomVersionDialog(this, builder.versionBundle) + .apply { + try { + //自定义dialog,commit button 必须存在 + val view = findViewById(R.id.versionchecklib_version_dialog_commit) + if (view != null) { + ALog.e("view not null") + view.setOnClickListener { + ALog.e("click") + dealVersionDialogCommit() + } + } else { + throwWrongIdsException() + } + //如果有取消按钮,id也必须对应 + val cancelView = findViewById(R.id.versionchecklib_version_dialog_cancel) + cancelView?.setOnClickListener { onCancel(this) } + } catch (e: Exception) { + e.printStackTrace() + throwWrongIdsException() + } + show() + + } + + } + + private fun showVersionDialog() { + BuilderManager.doWhenNotNull { + if (customVersionDialogListener != null) { + showCustomDialog() + } else { + showDefaultDialog() + } + } + versionDialog?.setOnCancelListener(this) + + } + + override fun onPause() { + super.onPause() + + versionDialog?.let { + if (it.isShowing) { + it.dismiss() + } + } + } + + override fun onResume() { + super.onResume() + versionDialog?.let { + if (!it.isShowing) { + it.show() + } + } + } + + private fun dealVersionDialogCommit() { + val versionBuilder: DownloadBuilder? = BuilderManager.getDownloadBuilder() + if (versionBuilder != null) { + //增加commit 回调 + if (versionBuilder.readyDownloadCommitClickListener != null) { + versionBuilder.readyDownloadCommitClickListener.onCommitClick() + } + //如果是静默下载直接安装 + if (versionBuilder.isSilentDownload) { + val downloadPath = versionBuilder.downloadAPKPath + getString(R.string.versionchecklib_download_apkname, if (versionBuilder.apkName != null) versionBuilder.apkName else packageName) + AppUtils.installApk(this, File(downloadPath), versionBuilder.customInstallListener) + checkForceUpdate() + //否定开始下载 + } else { + AllenEventBusUtil.sendEventBus(AllenEventType.START_DOWNLOAD_APK) + } + finish() + } + } + + override fun onCancel(dialogInterface: DialogInterface) { + cancelHandler() + checkForceUpdate() + AllenVersionChecker.getInstance().cancelAllMission() + finish() + } +} \ No newline at end of file diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java deleted file mode 100644 index bebc86e..0000000 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.java +++ /dev/null @@ -1,340 +0,0 @@ -package com.allenliu.versionchecklib.v2.ui; - -import android.app.IntentService; -import android.app.Service; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.Build; -import android.os.IBinder; - -import androidx.annotation.Nullable; -import androidx.annotation.WorkerThread; -import androidx.core.app.NotificationCompat; - -import com.allenliu.versionchecklib.R; -import com.allenliu.versionchecklib.callback.DownloadListener; -import com.allenliu.versionchecklib.core.DownloadManager; -import com.allenliu.versionchecklib.core.PermissionDialogActivity; -import com.allenliu.versionchecklib.core.http.AllenHttp; -import com.allenliu.versionchecklib.utils.ALog; -import com.allenliu.versionchecklib.utils.AllenEventBusUtil; -import com.allenliu.versionchecklib.utils.AppUtils; -import com.allenliu.versionchecklib.v2.AllenVersionChecker; -import com.allenliu.versionchecklib.v2.builder.BuilderManager; -import com.allenliu.versionchecklib.v2.builder.DownloadBuilder; -import com.allenliu.versionchecklib.v2.builder.VersionCheckBinder; -import com.allenliu.versionchecklib.v2.eventbus.AllenEventType; -import com.allenliu.versionchecklib.v2.eventbus.CommonEvent; -import com.allenliu.versionchecklib.v2.net.DownloadMangerV2; - -import org.greenrobot.eventbus.EventBus; -import org.greenrobot.eventbus.Subscribe; -import org.greenrobot.eventbus.ThreadMode; - -import java.io.File; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * An {@link IntentService} subclass for handling asynchronous task requests in - * a service on a separate handler thread. - *

- * TODO: Customize class - update intent actions, extra parameters and static - * helper methods. - */ -public class VersionService extends Service { - private DownloadBuilder builder; - private BuilderHelper builderHelper; - private NotificationHelper notificationHelper; - private boolean isServiceAlive = false; - private ExecutorService executors; - private VersionCheckBinder binder = new VersionCheckBinder(this); - - public void setBuilder(DownloadBuilder builder) { - this.builder = builder; - } - - public static void enqueueWork(final Context context, final DownloadBuilder builder) { - //清除之前的任务,如果有 - AllenVersionChecker.getInstance().cancelAllMission(); - BuilderManager.getInstance().setDownloadBuilder(builder); - Intent intent = new Intent(context, VersionService.class); - //显示通知栏的情况 才设置为前台服务 - if (builder.isRunOnForegroundService() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - context.startForegroundService(intent); - } else { - context.startService(intent); - } - ServiceConnection serviceConnection = new ServiceConnection() { - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - VersionCheckBinder binder = (VersionCheckBinder) service; - binder.setServiceConnection(this); - binder.setDownloadBuilder(builder); - } - - @Override - public void onServiceDisconnected(ComponentName name) { - - } - }; - context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - if (!EventBus.getDefault().isRegistered(this)) { - EventBus.getDefault().register(this); - } - ALog.e("version service create"); - //https://issuetracker.google.com/issues/76112072 - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - startForeground(NotificationHelper.NOTIFICATION_ID, NotificationHelper.createSimpleNotification(this)); -// init(); - return START_REDELIVER_INTENT; - } - - @Override - public void onDestroy() { - super.onDestroy(); - ALog.e("version service destroy"); - if (builder.isRunOnForegroundService()) - stopForeground(true); - builder.destory(); - BuilderManager.getInstance().destory(); - builderHelper = null; - if (notificationHelper != null) - notificationHelper.onDestroy(); - notificationHelper = null; - isServiceAlive = false; - if (executors != null) - executors.shutdown(); - AllenHttp.getHttpClient().dispatcher().cancelAll(); - if (EventBus.getDefault().isRegistered(this)) { - EventBus.getDefault().unregister(this); - } - } - - @Nullable - @Override - public IBinder onBind(Intent intent) { - return binder; - } - - - protected void onHandleWork() { - downloadAPK(); - } - - - private void downloadAPK() { - if (builder != null && builder.getVersionBundle() != null) { - if (builder.isDirectDownload()) { - AllenEventBusUtil.sendEventBus(AllenEventType.START_DOWNLOAD_APK); - } else { - if (builder.isSilentDownload()) { - requestPermissionAndDownload(); - } else { - showVersionDialog(); - } - } - } else { - AllenVersionChecker.getInstance().cancelAllMission(); - } - } - - - /** - * 开启UI展示界面 - */ - private void showVersionDialog() { - if (builder != null) { - Intent intent = new Intent(this, UIActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } - - private void showDownloadingDialog() { - if (builder != null && builder.isShowDownloadingDialog()) { - Intent intent = new Intent(this, DownloadingActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } - - private void updateDownloadingDialogProgress(int progress) { - CommonEvent commonEvent = new CommonEvent(); - commonEvent.setEventType(AllenEventType.UPDATE_DOWNLOADING_PROGRESS); - commonEvent.setData(progress); - commonEvent.setSuccessful(true); - EventBus.getDefault().post(commonEvent); - } - - private void showDownloadFailedDialog() { - if (builder != null) { - Intent intent = new Intent(this, DownloadFailedActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } - - private void requestPermissionAndDownload() { - if (builder != null) { - Intent intent = new Intent(this, PermissionDialogActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } - - private void install() { - AllenEventBusUtil.sendEventBus(AllenEventType.DOWNLOAD_COMPLETE); - final String downloadPath = getDownloadFilePath(); - if (builder.isSilentDownload()) { - showVersionDialog(); - } else { - AppUtils.installApk(getApplicationContext(), new File(downloadPath), builder.getCustomInstallListener()); - builderHelper.checkForceUpdate(); - } - } - - private String getDownloadFilePath() { - return builder.getDownloadAPKPath() + getString(R.string.versionchecklib_download_apkname, builder.getApkName() != null ? builder.getApkName() : getPackageName()); - } - - @WorkerThread - private void startDownloadApk() { - //判断是否缓存并且是否强制重新下载 - final String downloadPath = getDownloadFilePath(); - if (DownloadManager.checkAPKIsExists(getApplicationContext(), downloadPath, builder.getNewestVersionCode()) && !builder.isForceRedownload()) { - ALog.e("using cache"); - install(); - return; - } - builderHelper.checkAndDeleteAPK(); - String downloadUrl = builder.getDownloadUrl(); - if (downloadUrl == null && builder.getVersionBundle() != null) { - downloadUrl = builder.getVersionBundle().getDownloadUrl(); - } - if (downloadUrl == null) { - AllenVersionChecker.getInstance().cancelAllMission(); - throw new RuntimeException("you must set a download url for download function using"); - } - ALog.e("downloadPath:" + downloadPath); - - DownloadMangerV2.download(downloadUrl, builder.getDownloadAPKPath(), getString(R.string.versionchecklib_download_apkname, builder.getApkName() != null ? builder.getApkName() : getPackageName()), new DownloadListener() { - @Override - public void onCheckerDownloading(int progress) { - if (isServiceAlive && builder != null) { - if (!builder.isSilentDownload()) { - notificationHelper.updateNotification(progress); - updateDownloadingDialogProgress(progress); - } - if (builder.getApkDownloadListener() != null) - builder.getApkDownloadListener().onDownloading(progress); - } - } - - @Override - public void onCheckerDownloadSuccess(File file) { - if (isServiceAlive) { - if (!builder.isSilentDownload()) - notificationHelper.showDownloadCompleteNotifcation(file); - if (builder.getApkDownloadListener() != null) - builder.getApkDownloadListener().onDownloadSuccess(file); - install(); - } - } - - @Override - public void onCheckerDownloadFail() { - ALog.e("download failed"); - if (!isServiceAlive) - return; - if (builder.getApkDownloadListener() != null) - builder.getApkDownloadListener().onDownloadFail(); - if (!builder.isSilentDownload()) { - AllenEventBusUtil.sendEventBusStick(AllenEventType.CLOSE_DOWNLOADING_ACTIVITY); - if (builder.isShowDownloadFailDialog()) { - showDownloadFailedDialog(); - } - notificationHelper.showDownloadFailedNotification(); - } else { - AllenVersionChecker.getInstance().cancelAllMission(); - } - - } - - @Override - public void onCheckerStartDownload() { - ALog.e("start download apk"); - if (!builder.isSilentDownload()) { - notificationHelper.showNotification(); - showDownloadingDialog(); - } - } - }); - } - - - @Subscribe(threadMode = ThreadMode.MAIN) - public void receiveEvent(CommonEvent commonEvent) { - switch (commonEvent.getEventType()) { - case AllenEventType.START_DOWNLOAD_APK: - requestPermissionAndDownload(); - break; - case AllenEventType.REQUEST_PERMISSION: - boolean permissionResult = (boolean) commonEvent.getData(); - if (permissionResult) - startDownloadApk(); - else { - if (builderHelper != null) { - builderHelper.checkForceUpdate(); - } - - } - break; - case AllenEventType.STOP_SERVICE: - if (binder.getServiceConnection() != null) { - getApplicationContext().unbindService(binder.getServiceConnection()); - stopSelf(); - binder.setServiceConnection(null); - } - EventBus.getDefault().removeStickyEvent(commonEvent); - break; - - } - - } - - -// @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) -// public synchronized void onReceiveDownloadBuilder(DownloadBuilder downloadBuilder) { -// builder = downloadBuilder; -// init(); -// EventBus.getDefault().removeStickyEvent(downloadBuilder); -// } - - public void init() { - if (builder != null) { - isServiceAlive = true; - builderHelper = new BuilderHelper(getApplicationContext(), builder); - notificationHelper = new NotificationHelper(getApplicationContext(), builder); - if (builder.isRunOnForegroundService()) - startForeground(NotificationHelper.NOTIFICATION_ID, notificationHelper.getServiceNotification()); - executors = Executors.newSingleThreadExecutor(); - executors.submit(new Runnable() { - @Override - public void run() { - onHandleWork(); - } - }); - } else { - AllenVersionChecker.getInstance().cancelAllMission(); - } - } - - -} diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt new file mode 100644 index 0000000..9a35b0f --- /dev/null +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt @@ -0,0 +1,295 @@ +package com.allenliu.versionchecklib.v2.ui + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.IBinder +import androidx.annotation.WorkerThread +import com.allenliu.versionchecklib.R +import com.allenliu.versionchecklib.callback.DownloadListener +import com.allenliu.versionchecklib.core.DownloadManager +import com.allenliu.versionchecklib.core.PermissionDialogActivity +import com.allenliu.versionchecklib.core.http.AllenHttp +import com.allenliu.versionchecklib.utils.ALog +import com.allenliu.versionchecklib.utils.AllenEventBusUtil +import com.allenliu.versionchecklib.utils.AppUtils +import com.allenliu.versionchecklib.v2.AllenVersionChecker +import com.allenliu.versionchecklib.v2.builder.BuilderManager +import com.allenliu.versionchecklib.v2.builder.DownloadBuilder +import com.allenliu.versionchecklib.v2.callback.DownloadListenerKt +import com.allenliu.versionchecklib.v2.callback.LifecycleListener +import com.allenliu.versionchecklib.v2.eventbus.AllenEventType +import com.allenliu.versionchecklib.v2.eventbus.CommonEvent +import com.allenliu.versionchecklib.v2.net.DownloadMangerV2 +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode +import java.io.File +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors + +class VersionService : Service() { + private var notificationHelper: NotificationHelper? = null + private var isServiceAlive = false + private var executors: ExecutorService? = null + override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { + if (!EventBus.getDefault().isRegistered(this)) { + EventBus.getDefault().register(this) + } + ALog.e("version service create") + //https://issuetracker.google.com/issues/76112072 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForeground(NotificationHelper.NOTIFICATION_ID, NotificationHelper.createSimpleNotification(this)) + init() + return START_REDELIVER_INTENT + } + + companion object { + fun enqueueWork(context: Context, builder: DownloadBuilder) { + //清除之前的任务,如果有 +// AllenVersionChecker.getInstance().cancelAllMission() + BuilderManager.init(context, builder) + val intent = Intent(context, VersionService::class.java) + //显示通知栏的情况 才设置为前台服务 + if (builder.isRunOnForegroundService && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + } + } + + override fun onDestroy() { + super.onDestroy() + ALog.e("version service destroy") + BuilderManager.doWhenNotNull { + if (isRunOnForegroundService) { + stopForeground(true) + } + } + BuilderManager.destroy() + notificationHelper?.onDestroy() + isServiceAlive = false + executors?.shutdown() + AllenHttp.getHttpClient().dispatcher.cancelAll() + if (EventBus.getDefault().isRegistered(this)) { + EventBus.getDefault().unregister(this) + } + } + + override fun onBind(intent: Intent): IBinder? { + return null + } + + private fun onHandleWork() { + downloadAPK() + } + + private fun downloadAPK() { + BuilderManager.doWhenNotNull { + if (versionBundle != null) { + if (isDirectDownload) { + AllenEventBusUtil.sendEventBus(AllenEventType.START_DOWNLOAD_APK) + } else { + if (isSilentDownload) { + requestPermissionAndDownload() + } else { + showVersionDialog() + } + } + } + } + + } + + /** + * 开启UI展示界面 + */ + private fun showVersionDialog() { + BuilderManager.doWhenNotNull { + val intent = Intent(this@VersionService, UIActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + + } + + private fun showDownloadingDialog() { + BuilderManager.doWhenNotNull { + if (isShowDownloadingDialog) { + val intent = Intent(this@VersionService, DownloadingActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + + } + + } + + private fun updateDownloadingDialogProgress(progress: Int) { + val commonEvent: CommonEvent = CommonEvent() + commonEvent.eventType = AllenEventType.UPDATE_DOWNLOADING_PROGRESS + commonEvent.data = progress + commonEvent.isSuccessful = true + EventBus.getDefault().post(commonEvent) + } + + private fun showDownloadFailedDialog() { + BuilderManager.doWhenNotNull { + val intent = Intent(this@VersionService, DownloadFailedActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + + + } + + private fun requestPermissionAndDownload() { + BuilderManager.doWhenNotNull { + val intent = Intent(this@VersionService, PermissionDialogActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + + } + + private fun install() { + BuilderManager.doWhenNotNull { + AllenEventBusUtil.sendEventBus(AllenEventType.DOWNLOAD_COMPLETE) + val downloadPath = downloadFilePath + if (isSilentDownload) { + showVersionDialog() + } else { + AppUtils.installApk(applicationContext, File(downloadPath), customInstallListener) + BuilderManager.checkForceUpdate() + } + } + + } + + private val downloadFilePath: String + get() { + return BuilderManager.doWhenNotNull { + downloadAPKPath + getString(R.string.versionchecklib_download_apkname, if (apkName != null) apkName else packageName) + + } ?: "" + } + + @WorkerThread + private fun startDownloadApk() { + //判断是否缓存并且是否强制重新下载 + BuilderManager.doWhenNotNull { + val downloadPath = downloadFilePath + if (DownloadManager.checkAPKIsExists(applicationContext, downloadPath, getNewestVersionCode()) && !isForceRedownload()) { + ALog.e("using cache") + install() + return@doWhenNotNull + } + BuilderManager.checkAndDeleteAPK() + var downloadUrl: String? = downloadUrl + if (downloadUrl == null && versionBundle != null) { + downloadUrl = versionBundle.downloadUrl + } + if (downloadUrl == null) { + AllenVersionChecker.getInstance().cancelAllMission() + throw RuntimeException("you must set a download url for download function using") + } + ALog.e("downloadPath:$downloadPath") + DownloadMangerV2.download(downloadUrl, downloadAPKPath, getString(R.string.versionchecklib_download_apkname, if (apkName != null) apkName else packageName), downloadListener) + } + + } + + private val downloadListener: DownloadListenerKt = object : DownloadListenerKt { + override fun onCheckerDownloading(progress: Int) { + BuilderManager.doWhenNotNull { + if (isServiceAlive) { + if (!isSilentDownload) { + notificationHelper?.updateNotification(progress) + updateDownloadingDialogProgress(progress) + } + apkDownloadListener?.onDownloading(progress) + } + } + + } + + override fun onCheckerDownloadSuccess(file: File) { + BuilderManager.doWhenNotNull { + if (isServiceAlive) { + if (!isSilentDownload) notificationHelper?.showDownloadCompleteNotifcation(file) + apkDownloadListener?.onDownloadSuccess(file) + install() + } + } + + } + + + + override fun onCheckerDownloadFail() { + BuilderManager.doWhenNotNull { + ALog.e("download failed") + if (!isServiceAlive) return@doWhenNotNull + apkDownloadListener?.onDownloadFail() + if (!isSilentDownload) { + AllenEventBusUtil.sendEventBusStick(AllenEventType.CLOSE_DOWNLOADING_ACTIVITY) + if (isShowDownloadFailDialog) { + showDownloadFailedDialog() + } + notificationHelper?.showDownloadFailedNotification() + } else { + AllenVersionChecker.getInstance().cancelAllMission() + } + } + + } + + override fun onCheckerStartDownload() { + BuilderManager.doWhenNotNull { + ALog.e("start download apk") + if (!isSilentDownload) { + notificationHelper?.showNotification() + showDownloadingDialog() + } + } + + } + } + + @Subscribe(threadMode = ThreadMode.MAIN) + fun receiveEvent(commonEvent: CommonEvent<*>) { + when (commonEvent.eventType) { + AllenEventType.START_DOWNLOAD_APK -> requestPermissionAndDownload() + AllenEventType.REQUEST_PERMISSION -> { + val permissionResult = commonEvent.data as Boolean + if (permissionResult) startDownloadApk() else { + BuilderManager.checkForceUpdate() + } + } + AllenEventType.STOP_SERVICE -> { + stopSelf() + EventBus.getDefault().removeStickyEvent(commonEvent) + } + } + } + + // @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) + // public synchronized void onReceiveDownloadBuilder(DownloadBuilder downloadBuilder) { + // builder = downloadBuilder; + // init(); + // EventBus.getDefault().removeStickyEvent(downloadBuilder); + // } + private fun init() { + BuilderManager.doWhenNotNull { + isServiceAlive = true + notificationHelper = NotificationHelper(applicationContext) + if (isRunOnForegroundService) startForeground(NotificationHelper.NOTIFICATION_ID, notificationHelper?.serviceNotification) + executors = Executors.newSingleThreadExecutor() + executors?.submit { onHandleWork() } + } + + } + + +} \ No newline at end of file From dd302fd2dc6aec118e97b8c815c83e14520830f9 Mon Sep 17 00:00:00 2001 From: shengliu7 <29949821@qq.com> Date: Sat, 19 Dec 2020 15:51:03 +0800 Subject: [PATCH 5/5] feat:use kotlin implementation some class and fix bugs --- library/build.gradle | 4 +-- .../versionchecklib/utils/FileHelper.java | 11 ++++-- .../v2/builder/DownloadBuilder.java | 15 ++++---- .../versionchecklib/v2/ui/VersionService.kt | 1 + sample/build.gradle | 4 +-- sample/src/main/AndroidManifest.xml | 2 ++ .../com/allenliu/sample/v2/V2Activity.java | 35 +++++++++++++++++-- 7 files changed, 57 insertions(+), 15 deletions(-) diff --git a/library/build.gradle b/library/build.gradle index c4ed90b..d19fb1b 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -3,7 +3,7 @@ apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 29 - buildToolsVersion "29.0.3" +// buildToolsVersion "29.0.3" resourcePrefix "versionchecklib" defaultConfig { minSdkVersion 14 @@ -26,7 +26,7 @@ android { dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') - implementation 'androidx.appcompat:appcompat:1.1.0' + compileOnly 'androidx.appcompat:appcompat:1.1.0' implementation 'com.squareup.okhttp3:okhttp:4.3.1' implementation 'org.greenrobot:eventbus:3.1.1' diff --git a/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java b/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java index 10592e6..ba3e714 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java +++ b/library/src/main/java/com/allenliu/versionchecklib/utils/FileHelper.java @@ -1,12 +1,13 @@ package com.allenliu.versionchecklib.utils; import android.content.Context; +import android.os.Build; import android.os.Environment; -import java.io.File; - import androidx.annotation.NonNull; +import java.io.File; + public class FileHelper { @Deprecated public static String getDownloadApkCachePath() { @@ -30,7 +31,11 @@ public static String getDownloadApkCachePath() { public static String getDownloadApkCachePath(Context context) { String appCachePath; if (checkSDCard()) { - appCachePath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/AllenVersionPath/"; + if (Build.VERSION.SDK_INT >= 29) { + appCachePath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/AllenVersionPath/"; + } else { + appCachePath = context.getExternalCacheDir() + "/AllenVersionPath/"; + } } else { appCachePath = context.getFilesDir().getAbsolutePath() + "/AllenVersionPath/"; diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java index 1bbbe07..01cc5a6 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/builder/DownloadBuilder.java @@ -306,12 +306,7 @@ public DownloadBuilder setDirectDownload(boolean directDownload) { return this; } - public void executeMission(Context context) { - if (apkName == null) { - //https://github.com/AlexLiuSheng/CheckVersionLib/issues/338 - apkName = context.getApplicationContext().getPackageName().replaceAll("\\.", ""); - } - + private void setupDefaultNotificationIcon(Context context) { if (notificationBuilder.getIcon() == 0) { final PackageManager pm = context.getPackageManager(); final ApplicationInfo applicationInfo; @@ -323,6 +318,14 @@ public void executeMission(Context context) { e.printStackTrace(); } } + } + + public void executeMission(Context context) { + if (apkName == null) { + //https://github.com/AlexLiuSheng/CheckVersionLib/issues/338 + apkName = context.getApplicationContext().getPackageName().replaceAll("\\.", ""); + } + setupDefaultNotificationIcon(context); //fix path permission setupDownloadPath(context); // downloadAPKPath=context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() + "/"; diff --git a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt index 9a35b0f..016514d 100644 --- a/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt +++ b/library/src/main/java/com/allenliu/versionchecklib/v2/ui/VersionService.kt @@ -265,6 +265,7 @@ class VersionService : Service() { val permissionResult = commonEvent.data as Boolean if (permissionResult) startDownloadApk() else { BuilderManager.checkForceUpdate() + AllenVersionChecker.getInstance().cancelAllMission() } } AllenEventType.STOP_SERVICE -> { diff --git a/sample/build.gradle b/sample/build.gradle index daf9fa3..e872740 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -1,11 +1,11 @@ apply plugin: 'com.android.application' //apply plugin: 'me.tatarka.retrolambda' android { - compileSdkVersion 29 + compileSdkVersion 28 defaultConfig { applicationId "com.allenliu.sample" minSdkVersion 16 - targetSdkVersion 29 + targetSdkVersion 28 versionCode 1 versionName "1.0" diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml index 20fcc43..92d5ebe 100644 --- a/sample/src/main/AndroidManifest.xml +++ b/sample/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ diff --git a/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java b/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java index c663add..fb5e682 100644 --- a/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java +++ b/sample/src/main/java/com/allenliu/sample/v2/V2Activity.java @@ -3,7 +3,6 @@ import android.app.Dialog; import android.content.Context; import android.os.Bundle; -import android.os.Environment; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; @@ -49,7 +48,7 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_v2); initView(); - +// sendDefaultReuqest(); } private void initView() { @@ -80,6 +79,38 @@ public void v2Click(View view) { break; } } + private void sendDefaultReuqest(){ + builder = AllenVersionChecker + .getInstance() + .requestVersion() + .setRequestUrl("https://www.baidu.com") + + .request(new RequestVersionListener() { + @Nullable + @Override + public UIData onRequestVersionSuccess(DownloadBuilder downloadBuilder,String result) { +// V2.1.1可以根据服务器返回的结果,动态在此设置是否强制更新等 +// downloadBuilder.setForceUpdateListener(() -> { +// forceUpdate(); +// }); + Toast.makeText(V2Activity.this, "request successful", Toast.LENGTH_SHORT).show(); + return crateUIData(); + } + + @Override + public void onRequestVersionFailure(String message) { + Toast.makeText(V2Activity.this, "request failed", Toast.LENGTH_SHORT).show(); + + } + }); + builder.setCustomVersionDialogListener(createCustomDialogTwo()); + builder.setCustomDownloadingDialogListener(createCustomDownloadingDialog()); + builder.setCustomDownloadFailedListener(createCustomDownloadFailedDialog()); + builder.setForceRedownload(true); + + builder.executeMission(this); + + } private void sendRequest() {