@capgo/capacitor-updater 9.0.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2406 -291
  4. package/android/build.gradle +37 -17
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +963 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2641 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +876 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1109 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -1,8 +1,9 @@
1
1
  ext {
2
2
  junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
3
- androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1'
4
- androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.1.5'
5
- androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.5.1'
3
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.8.0'
4
+ androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
5
+ androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
6
+ okhttpVersion = project.hasProperty('okhttpVersion') ? rootProject.ext.okhttpVersion : '4.12.0'
6
7
  }
7
8
 
8
9
  buildscript {
@@ -11,34 +12,32 @@ buildscript {
11
12
  mavenCentral()
12
13
  }
13
14
  dependencies {
14
- classpath 'com.android.tools.build:gradle:8.0.1'
15
+ classpath 'com.android.tools.build:gradle:9.4.1'
15
16
  }
16
17
  }
17
18
 
18
19
  apply plugin: 'com.android.library'
19
20
 
20
21
  android {
21
- namespace "ee.forgr.capacitor_updater"
22
- compileSdkVersion project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 33
22
+ namespace = "ee.forgr.capacitor_updater"
23
+ compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 37
23
24
  defaultConfig {
24
- minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
25
- targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 33
26
- versionCode 1
27
- versionName "1.0"
25
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 26
28
26
  testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
27
+ consumerProguardFiles 'consumer-rules.pro'
29
28
  }
30
29
  buildTypes {
31
30
  release {
32
31
  minifyEnabled false
33
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
32
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
34
33
  }
35
34
  }
36
35
  lintOptions {
37
- abortOnError false
36
+ abortOnError = false
38
37
  }
39
38
  compileOptions {
40
- sourceCompatibility JavaVersion.VERSION_17
41
- targetCompatibility JavaVersion.VERSION_17
39
+ sourceCompatibility JavaVersion.VERSION_21
40
+ targetCompatibility JavaVersion.VERSION_21
42
41
  }
43
42
  }
44
43
 
@@ -49,13 +48,34 @@ repositories {
49
48
 
50
49
 
51
50
  dependencies {
51
+ def work_version = "2.10.5"
52
+ def lifecycle_version = "2.10.0"
53
+ implementation "androidx.work:work-runtime:$work_version"
54
+ implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
55
+ implementation "com.google.android.gms:play-services-tasks:18.4.1"
52
56
  implementation fileTree(dir: 'libs', include: ['*.jar'])
53
57
  implementation project(':capacitor-android')
54
58
  implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
55
- implementation 'com.android.volley:volley:1.2.1'
56
- implementation 'io.github.g00fy2:versioncompare:1.5.0'
57
- implementation 'com.google.code.gson:gson:2.10.1'
59
+ // Play Core library for in-app updates
60
+ implementation 'com.google.android.play:app-update:2.1.0'
58
61
  testImplementation "junit:junit:$junitVersion"
62
+ testImplementation 'org.mockito:mockito-core:5.25.0'
63
+ testImplementation 'org.json:json:20250517'
64
+ testImplementation 'org.robolectric:robolectric:4.18'
65
+ testImplementation 'androidx.arch.core:core-testing:2.2.0'
66
+ testImplementation "com.squareup.okhttp3:mockwebserver:$okhttpVersion"
59
67
  androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
60
68
  androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
69
+ implementation 'org.brotli:dec:0.1.2'
70
+ implementation "com.squareup.okhttp3:okhttp:$okhttpVersion"
71
+ }
72
+
73
+ tasks.withType(Test) {
74
+ testLogging {
75
+ events "passed", "skipped", "failed", "standardOut", "standardError"
76
+ exceptionFormat "full"
77
+ showStandardStreams = true
78
+ showCauses = true
79
+ showStackTraces = true
80
+ }
61
81
  }
@@ -0,0 +1,48 @@
1
+ # Consumer ProGuard / R8 rules: merged into apps that depend on this library (Capacitor 9 enables release minify by default).
2
+
3
+ # Capacitor reflects plugin classes and @PluginMethod entries; keep this plugin and its methods.
4
+ -keep @com.getcapacitor.annotation.CapacitorPlugin class ee.forgr.capacitor_updater.CapacitorUpdaterPlugin { *; }
5
+ -keepclassmembers class ee.forgr.capacitor_updater.CapacitorUpdaterPlugin {
6
+ @com.getcapacitor.PluginMethod <methods>;
7
+ }
8
+
9
+ # Inner types on the plugin (for example autoSplashscreen helper call construction).
10
+ -keep class ee.forgr.capacitor_updater.CapacitorUpdaterPlugin$* { *; }
11
+
12
+ # Splash automation calls other plugins through PluginHandle; Capacitor may route that by name, so keep invoke.
13
+ -keepclassmembers class * implements com.getcapacitor.PluginHandle {
14
+ public void invoke(java.lang.String, com.getcapacitor.PluginCall);
15
+ }
16
+
17
+ # FireAndForgetPluginCall supplies a null MessageHandler; keep the constructor signature PluginCall uses at runtime.
18
+ -keep class com.getcapacitor.PluginCall {
19
+ <init>(com.getcapacitor.MessageHandler, java.lang.String, java.lang.String, java.lang.String, com.getcapacitor.JSObject);
20
+ }
21
+
22
+ # Constructor parameter type for the kept PluginCall signature above.
23
+ -keep class com.getcapacitor.MessageHandler { *; }
24
+
25
+ # Optional Background Runner integration: Class.forName for the worker when that plugin is installed.
26
+ -keep class io.ionic.backgroundrunner.plugin.RunnerWorker {
27
+ <init>(android.content.Context, androidx.work.WorkerParameters);
28
+ }
29
+
30
+ # Document start script support reflects WebViewFeature and WebViewCompat by name on older API levels.
31
+ -keepclassmembers class androidx.webkit.WebViewFeature {
32
+ public static final java.lang.String DOCUMENT_START_SCRIPT;
33
+ public static boolean isFeatureSupported(java.lang.String);
34
+ }
35
+ -keep class androidx.webkit.WebViewCompat {
36
+ public static void addDocumentStartJavaScript(android.webkit.WebView, java.lang.String, java.util.Set);
37
+ }
38
+
39
+ # WorkManager constructs these worker classes by class object or class name at runtime.
40
+ -keepclassmembers class ee.forgr.capacitor_updater.DownloadService {
41
+ <init>(android.content.Context, androidx.work.WorkerParameters);
42
+ }
43
+ -keepclassmembers class ee.forgr.capacitor_updater.HeadlessUpdateWorker {
44
+ <init>(android.content.Context, androidx.work.WorkerParameters);
45
+ }
46
+
47
+ # Used by Capacitor and androidx APIs that read annotations and generic types at runtime.
48
+ -keepattributes *Annotation*, Signature
@@ -0,0 +1,23 @@
1
+ # Add project specific ProGuard rules here.
2
+ # You can control the set of applied configuration files using the
3
+ # proguardFiles setting in build.gradle.
4
+ #
5
+ # For more details, see
6
+ # http://developer.android.com/guide/developing/tools/proguard.html
7
+
8
+ # If your project uses WebView with JS, uncomment the following
9
+ # and specify the fully qualified class name to the JavaScript interface
10
+ # class:
11
+ #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12
+ # public *;
13
+ #}
14
+
15
+ # Uncomment this to preserve the line number information for
16
+ # debugging stack traces.
17
+ #-keepattributes SourceFile,LineNumberTable
18
+
19
+ # If you keep the line number information, uncomment this to
20
+ # hide the original source file name.
21
+ #-renamesourcefileattribute SourceFile
22
+
23
+ # Rules needed by consuming apps ship in consumer-rules.pro (see consumerProguardFiles in build.gradle).
@@ -1,5 +1,4 @@
1
1
  <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
2
  <application>
3
- <service android:name="ee.forgr.capacitor_updater.DownloadService" />
4
3
  </application>
5
4
  </manifest>
@@ -0,0 +1,92 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ import android.annotation.TargetApi;
10
+ import android.app.ActivityManager;
11
+ import android.app.ApplicationExitInfo;
12
+ import android.content.Context;
13
+ import android.content.SharedPreferences;
14
+ import android.os.Build;
15
+ import java.util.HashMap;
16
+ import java.util.List;
17
+ import java.util.Map;
18
+
19
+ @TargetApi(Build.VERSION_CODES.R)
20
+ final class AndroidAppExitReporter {
21
+
22
+ private AndroidAppExitReporter() {}
23
+
24
+ static void reportPreviousAppExitReasons(
25
+ final Context context,
26
+ final SharedPreferences prefs,
27
+ final CapgoUpdater implementation,
28
+ final Logger logger,
29
+ final String lastReportedAppExitTimestampPrefKey
30
+ ) {
31
+ try {
32
+ final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
33
+ if (activityManager == null) {
34
+ return;
35
+ }
36
+
37
+ final List<ApplicationExitInfo> exitReasons = activityManager.getHistoricalProcessExitReasons(context.getPackageName(), 0, 8);
38
+ if (exitReasons == null || exitReasons.isEmpty()) {
39
+ return;
40
+ }
41
+
42
+ final long lastReportedTimestamp = prefs.getLong(lastReportedAppExitTimestampPrefKey, 0L);
43
+ long newestReportedTimestamp = lastReportedTimestamp;
44
+ final BundleInfo current = implementation.getCurrentBundle();
45
+ final String versionName = current == null ? "" : current.getVersionName();
46
+
47
+ for (final ApplicationExitInfo exitInfo : exitReasons) {
48
+ if (exitInfo == null || exitInfo.getTimestamp() <= lastReportedTimestamp) {
49
+ continue;
50
+ }
51
+
52
+ final String action = CapacitorUpdaterPlugin.statsActionForApplicationExitReason(exitInfo.getReason());
53
+ if (action == null) {
54
+ continue;
55
+ }
56
+
57
+ implementation.sendStats(action, versionName, "", buildApplicationExitMetadata(exitInfo));
58
+ newestReportedTimestamp = Math.max(newestReportedTimestamp, exitInfo.getTimestamp());
59
+ }
60
+
61
+ if (newestReportedTimestamp > lastReportedTimestamp) {
62
+ prefs.edit().putLong(lastReportedAppExitTimestampPrefKey, newestReportedTimestamp).apply();
63
+ }
64
+ } catch (final Exception e) {
65
+ logger.warn("Unable to report previous app exit reason: " + e.getMessage());
66
+ }
67
+ }
68
+
69
+ private static Map<String, String> buildApplicationExitMetadata(final ApplicationExitInfo exitInfo) {
70
+ final Map<String, String> metadata = new HashMap<>();
71
+ metadata.put("exit_reason", CapacitorUpdaterPlugin.applicationExitReasonName(exitInfo.getReason()));
72
+ metadata.put("exit_reason_code", Integer.toString(exitInfo.getReason()));
73
+ metadata.put("exit_status", Integer.toString(exitInfo.getStatus()));
74
+ metadata.put("exit_importance", Integer.toString(exitInfo.getImportance()));
75
+ metadata.put("exit_timestamp", Long.toString(exitInfo.getTimestamp()));
76
+ metadata.put("pid", Integer.toString(exitInfo.getPid()));
77
+ metadata.put("pss_kb", Long.toString(exitInfo.getPss()));
78
+ metadata.put("rss_kb", Long.toString(exitInfo.getRss()));
79
+
80
+ final String processName = exitInfo.getProcessName();
81
+ if (processName != null && !processName.isEmpty()) {
82
+ metadata.put("process_name", CapacitorUpdaterPlugin.truncateStatsMetadataValue(processName, 128));
83
+ }
84
+
85
+ final String description = exitInfo.getDescription();
86
+ if (description != null && !description.isEmpty()) {
87
+ metadata.put("exit_description", CapacitorUpdaterPlugin.truncateStatsMetadataValue(description, 512));
88
+ }
89
+
90
+ return metadata;
91
+ }
92
+ }
@@ -0,0 +1,115 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ import android.content.Context;
10
+ import androidx.annotation.NonNull;
11
+ import androidx.lifecycle.DefaultLifecycleObserver;
12
+ import androidx.lifecycle.LifecycleOwner;
13
+ import androidx.lifecycle.ProcessLifecycleInitializer;
14
+ import androidx.lifecycle.ProcessLifecycleOwner;
15
+ import androidx.startup.AppInitializer;
16
+
17
+ /**
18
+ * Observes app-level lifecycle events using ProcessLifecycleOwner.
19
+ * This provides reliable detection of when the entire app (not just an activity)
20
+ * moves to foreground or background.
21
+ *
22
+ * Unlike activity lifecycle callbacks, this won't trigger false positives when:
23
+ * - Opening a native camera view
24
+ * - Opening share sheets
25
+ * - Any other native activity overlays within the app
26
+ *
27
+ * The ON_STOP event is dispatched with a ~700ms delay after the last activity
28
+ * passes through onStop(), which helps avoid false triggers during configuration
29
+ * changes or quick activity transitions.
30
+ */
31
+ public class AppLifecycleObserver implements DefaultLifecycleObserver {
32
+
33
+ public interface AppLifecycleListener {
34
+ void onAppMovedToForeground();
35
+ void onAppMovedToBackground();
36
+ }
37
+
38
+ private final AppLifecycleListener listener;
39
+ private final Logger logger;
40
+ private boolean isRegistered = false;
41
+
42
+ public AppLifecycleObserver(AppLifecycleListener listener, Logger logger) {
43
+ this.listener = listener;
44
+ this.logger = logger;
45
+ }
46
+
47
+ public boolean isRegistered() {
48
+ return isRegistered;
49
+ }
50
+
51
+ public void register(Context context) {
52
+ if (isRegistered) {
53
+ return;
54
+ }
55
+ if (context == null) {
56
+ logger.error("Cannot register AppLifecycleObserver without context");
57
+ return;
58
+ }
59
+ // get()/addObserver() succeed even when ProcessLifecycleOwner.init() never ran.
60
+ // Initialize first; if that fails, leave isRegistered false so activity fallback runs.
61
+ try {
62
+ AppInitializer.getInstance(context.getApplicationContext()).initializeComponent(ProcessLifecycleInitializer.class);
63
+ } catch (Exception e) {
64
+ logger.error("Failed to initialize ProcessLifecycleOwner: " + e.getMessage());
65
+ return;
66
+ }
67
+ if (!addObserver()) {
68
+ logger.error("Failed to register AppLifecycleObserver with ProcessLifecycleOwner");
69
+ }
70
+ }
71
+
72
+ private boolean addObserver() {
73
+ try {
74
+ ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
75
+ isRegistered = true;
76
+ logger.info("AppLifecycleObserver registered with ProcessLifecycleOwner");
77
+ return true;
78
+ } catch (Exception e) {
79
+ logger.error("Failed to add AppLifecycleObserver: " + e.getMessage());
80
+ return false;
81
+ }
82
+ }
83
+
84
+ public void unregister() {
85
+ if (!isRegistered) {
86
+ return;
87
+ }
88
+ try {
89
+ ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
90
+ isRegistered = false;
91
+ logger.info("AppLifecycleObserver unregistered from ProcessLifecycleOwner");
92
+ } catch (Exception e) {
93
+ logger.error("Failed to unregister AppLifecycleObserver: " + e.getMessage());
94
+ }
95
+ }
96
+
97
+ @Override
98
+ public void onStart(@NonNull LifecycleOwner owner) {
99
+ // App moved to foreground (at least one activity is visible)
100
+ logger.info("ProcessLifecycleOwner: App moved to foreground");
101
+ if (listener != null) {
102
+ listener.onAppMovedToForeground();
103
+ }
104
+ }
105
+
106
+ @Override
107
+ public void onStop(@NonNull LifecycleOwner owner) {
108
+ // App moved to background (no activities are visible)
109
+ // Note: This is called with a ~700ms delay to avoid false triggers
110
+ logger.info("ProcessLifecycleOwner: App moved to background");
111
+ if (listener != null) {
112
+ listener.onAppMovedToBackground();
113
+ }
114
+ }
115
+ }