Skip to content

Commit

Permalink
Switch to AlarmManager plugin from WorkManager for more reliable upda…
Browse files Browse the repository at this point in the history
…te checking (for #87) (#97)
  • Loading branch information
ImranR98 committed Nov 6, 2022
1 parent bd5f219 commit ed4a26d
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 57 deletions.
18 changes: 18 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,25 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<service
android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false"/>
<receiver
android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmBroadcastReceiver"
android:exported="false"/>
<receiver
android:name="dev.fluttercommunity.plus.androidalarmmanager.RebootBroadcastReceiver"
android:enabled="false"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
</manifest>
57 changes: 23 additions & 34 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
Expand All @@ -10,18 +11,21 @@ import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:workmanager/workmanager.dart';
import 'package:dynamic_color/dynamic_color.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';

const String currentVersion = '0.6.6';
const String currentVersion = '0.6.7';
const String currentReleaseTag =
'v$currentVersion-beta'; // KEEP THIS IN SYNC WITH GITHUB RELEASES

const String bgUpdateCheckTaskName = 'bg-update-check';
const int bgUpdateCheckAlarmId = 666;

bgUpdateCheck(int? ignoreAfterMicroseconds) async {
@pragma('vm:entry-point')
Future<void> bgUpdateCheck(int taskId, Map<String, dynamic>? params) async {
int? ignoreAfterMicroseconds = params?['ignoreAfterMicroseconds'];
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
DateTime? ignoreAfter = ignoreAfterMicroseconds != null
? DateTime.fromMicrosecondsSinceEpoch(ignoreAfterMicroseconds)
: null;
Expand All @@ -43,13 +47,13 @@ bgUpdateCheck(int? ignoreAfterMicroseconds) async {
shouldCorrectInstallStatus: false);
} catch (e) {
if (e is RateLimitError || e is SocketException) {
String nextTaskName =
'$bgUpdateCheckTaskName-${nextIgnoreAfter.microsecondsSinceEpoch.toString()}';
Workmanager().registerOneOffTask(nextTaskName, nextTaskName,
constraints: Constraints(networkType: NetworkType.connected),
initialDelay: Duration(
minutes: e is RateLimitError ? e.remainingMinutes : 15),
inputData: {'ignoreAfter': nextIgnoreAfter.microsecondsSinceEpoch});
AndroidAlarmManager.oneShot(
Duration(minutes: e is RateLimitError ? e.remainingMinutes : 15),
Random().nextInt(pow(2, 31) as int),
bgUpdateCheck,
params: {
'ignoreAfterMicroseconds': nextIgnoreAfter.microsecondsSinceEpoch
});
} else {
err = e.toString();
}
Expand Down Expand Up @@ -80,24 +84,14 @@ bgUpdateCheck(int? ignoreAfterMicroseconds) async {
if (err != null) {
throw err;
}
return Future.value(true);
} catch (e) {
notificationsProvider
.notify(ErrorCheckingUpdatesNotification(e.toString()));
return Future.error(false);
} finally {
await notificationsProvider.cancel(checkingUpdatesNotification.id);
}
}

@pragma('vm:entry-point')
void bgTaskCallback() {
// Background process callback
Workmanager().executeTask((task, inputData) async {
return await bgUpdateCheck(inputData?['ignoreAfter']);
});
}

void main() async {
WidgetsFlutterBinding.ensureInitialized();
if ((await DeviceInfoPlugin().androidInfo).version.sdkInt >= 29) {
Expand All @@ -106,9 +100,7 @@ void main() async {
);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
}
Workmanager().initialize(
bgTaskCallback,
);
await AndroidAlarmManager.initialize();
runApp(MultiProvider(
providers: [
ChangeNotifierProvider(
Expand Down Expand Up @@ -165,17 +157,14 @@ class _ObtainiumState extends State<Obtainium> {
if (existingUpdateInterval != settingsProvider.updateInterval) {
existingUpdateInterval = settingsProvider.updateInterval;
if (existingUpdateInterval == 0) {
Workmanager().cancelByUniqueName(bgUpdateCheckTaskName);
AndroidAlarmManager.cancel(bgUpdateCheckAlarmId);
} else {
Workmanager().registerPeriodicTask(
bgUpdateCheckTaskName, bgUpdateCheckTaskName,
frequency: Duration(minutes: existingUpdateInterval),
initialDelay: Duration(minutes: existingUpdateInterval),
constraints: Constraints(networkType: NetworkType.connected),
existingWorkPolicy: ExistingWorkPolicy.replace,
backoffPolicy: BackoffPolicy.linear,
backoffPolicyDelay:
const Duration(minutes: minUpdateIntervalMinutes));
AndroidAlarmManager.periodic(
Duration(minutes: existingUpdateInterval),
bgUpdateCheckAlarmId,
bgUpdateCheck,
rescheduleOnReboot: true,
wakeup: true);
}
}
}
Expand Down
11 changes: 0 additions & 11 deletions lib/pages/settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -209,17 +209,6 @@ class _SettingsPageState extends State<SettingsPage> {
settingsProvider.updateInterval = value;
}
}),
const SizedBox(
height: 8,
),
Text(
'Longer intervals may result in less reliable behaviour',
style: Theme.of(context)
.textTheme
.labelMedium!
.merge(const TextStyle(
fontStyle: FontStyle.italic)),
),
const Divider(
height: 48,
),
Expand Down
2 changes: 1 addition & 1 deletion lib/providers/settings_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class SettingsProvider with ChangeNotifier {
}

int get updateInterval {
var min = prefs?.getInt('updateInterval') ?? 60;
var min = prefs?.getInt('updateInterval') ?? 360;
if (!updateIntervals.contains(min)) {
var temp = updateIntervals[0];
for (var i in updateIntervals) {
Expand Down
18 changes: 9 additions & 9 deletions pubspec.lock
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
android_alarm_manager_plus:
dependency: "direct main"
description:
name: android_alarm_manager_plus
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
animations:
dependency: "direct main"
description:
Expand Down Expand Up @@ -358,7 +365,7 @@ packages:
name: path_provider_android
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.20"
version: "2.0.21"
path_provider_ios:
dependency: transitive
description:
Expand Down Expand Up @@ -470,7 +477,7 @@ packages:
name: share_plus
url: "https://pub.dartlang.org"
source: hosted
version: "6.1.0"
version: "6.2.0"
share_plus_platform_interface:
dependency: transitive
description:
Expand Down Expand Up @@ -700,13 +707,6 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.1"
workmanager:
dependency: "direct main"
description:
name: workmanager
url: "https://pub.dartlang.org"
source: hosted
version: "0.5.1"
xdg_directories:
dependency: transitive
description:
Expand Down
4 changes: 2 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 0.6.6+50 # When changing this, update the tag in main() accordingly
version: 0.6.7+51 # When changing this, update the tag in main() accordingly

environment:
sdk: '>=2.18.2 <3.0.0'
Expand All @@ -42,7 +42,6 @@ dependencies:
provider: ^6.0.3
http: ^0.13.5
webview_flutter: ^3.0.4
workmanager: ^0.5.0
dynamic_color: ^1.5.4
html: ^0.15.0
shared_preferences: ^2.0.15
Expand All @@ -56,6 +55,7 @@ dependencies:
share_plus: ^6.0.1
installed_apps: ^1.3.1
package_archive_info: ^0.1.0
android_alarm_manager_plus: ^2.1.0


dev_dependencies:
Expand Down

0 comments on commit ed4a26d

Please sign in to comment.