Skip to content

Commit

Permalink
reworked background task with android_alarm_manager_plus
Browse files Browse the repository at this point in the history
  • Loading branch information
Rakibul73 committed Apr 26, 2023
1 parent def5805 commit 91dc6e5
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 37 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ flutter run
- [Android Intent Plus](https://pub.dev/packages/android_intent_plus) library for alarm
- removed ~~[Flutter Alarm Clock](https://pub.dev/packages/flutter_alarm_clock) library for making an alarm~~
- [Twitter Tweets API](https://github.com/Rakibul73/twitter_tweets_api)
- [WorkManager](https://pub.dev/packages/workmanager) library for making periodic task
- [Android Alarm Manager Plus](https://pub.dev/packages/android_alarm_manager_plus) library for making background task
- removed ~~[WorkManager](https://pub.dev/packages/workmanager) library for making background task~~
- [SharedPreferences](https://pub.dev/packages/shared_preferences) library for persistent storage
- [Twitter Developer API](https://developer.twitter.com/en/docs)
2 changes: 0 additions & 2 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
package="com.spryshanto.cr_alarm">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- For apps with targetSDK=31 (Android 12) -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
Expand Down
42 changes: 21 additions & 21 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:permission_handler/permission_handler.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:android_intent_plus/android_intent.dart';
import 'package:android_intent_plus/flag.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workmanager/workmanager.dart';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:platform/platform.dart';


const simplePeriodicTask = "simplePeriodicTask";
const latestTimestampKey = "latestTimestamp";

@pragma('vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
await _createAlarm();
// Return true when the task is completed successfully
return Future.value(true);
});
}

class PostHttpOverrides extends HttpOverrides{
@override
HttpClient createHttpClient(context){
Expand All @@ -32,6 +23,7 @@ class PostHttpOverrides extends HttpOverrides{
}
}

@pragma('vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+
Future<void> _createAlarm() async {
// Retrieve the latest timestamp from shared preferences
final prefs = await SharedPreferences.getInstance();
Expand All @@ -41,7 +33,6 @@ Future<void> _createAlarm() async {
if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
final String timestamp = data['timestamp'];
const int timeZoneDifferenceInHours = 6;
// Checking if the timestamp has changed or not
if (timestamp != latestTimestamp) {
// saving the latest timestamp to shared preferences for next time
Expand All @@ -66,15 +57,12 @@ Future<void> _createAlarm() async {
'android.intent.extra.alarm.MESSAGE': 'CR Posted',
},
);
intent.launch();
await intent.launch();
}
catch (e) {
print('Error creating alarm: callbackDispatcher= $e');
throw Exception('Error creating alarm: $e');
}
}
else {
print("\ntimestamp === latestTimestamp\n");
}
}
else {
throw Exception('Failed to load data from API');
Expand All @@ -84,15 +72,19 @@ Future<void> _createAlarm() async {
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
HttpOverrides.global = new PostHttpOverrides();
Workmanager().initialize(callbackDispatcher);
// Registering periodic task for every 15 minutes
Workmanager().registerPeriodicTask(simplePeriodicTask , simplePeriodicTask,
frequency: const Duration(minutes: 15));
await AndroidAlarmManager.initialize();
await AndroidAlarmManager.periodic(const Duration(minutes: 5), 4, _createAlarm,
exact: true,
wakeup: true,
allowWhileIdle: true,
rescheduleOnReboot: true);

runApp(MyApp());
}

class MyApp extends StatefulWidget {
const MyApp({super.key});

@override
_MyAppState createState() => _MyAppState();
}
Expand All @@ -101,6 +93,14 @@ class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
requestPermissions();
}

Future<void> requestPermissions() async {
PermissionStatus status = await Permission.ignoreBatteryOptimizations.status;
if (!status.isGranted) {
status = await Permission.ignoreBatteryOptimizations.request();
}
}

@override
Expand Down
60 changes: 50 additions & 10 deletions pubspec.lock
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
# 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
sha256: "8160e431426c9419d91e3e72c45e2d67be9cfbdbaa942bfd43d58ade04cb1632"
url: "https://pub.dev"
source: hosted
version: "2.1.3"
android_intent_plus:
dependency: "direct main"
description:
name: android_intent_plus
sha256: "6bcdcd20461ac7a0c785f6298cdda96ad275d5bcbc1ecf28829cbe03ec6690be"
sha256: "28a665a6cd505a03ba480d78a36a1959c24de0c32083dd1e82766c99299cfca3"
url: "https://pub.dev"
source: hosted
version: "3.1.7"
version: "3.1.8"
archive:
dependency: transitive
description:
Expand Down Expand Up @@ -272,6 +280,46 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.5"
permission_handler:
dependency: "direct main"
description:
name: permission_handler
sha256: "33c6a1253d1f95fd06fa74b65b7ba907ae9811f9d5c1d3150e51417d04b8d6a8"
url: "https://pub.dev"
source: hosted
version: "10.2.0"
permission_handler_android:
dependency: transitive
description:
name: permission_handler_android
sha256: "8028362b40c4a45298f1cbfccd227c8dd6caf0e27088a69f2ba2ab15464159e2"
url: "https://pub.dev"
source: hosted
version: "10.2.0"
permission_handler_apple:
dependency: transitive
description:
name: permission_handler_apple
sha256: ee96ac32f5a8e6f80756e25b25b9f8e535816c8e6665a96b6d70681f8c4f7e85
url: "https://pub.dev"
source: hosted
version: "9.0.8"
permission_handler_platform_interface:
dependency: transitive
description:
name: permission_handler_platform_interface
sha256: "68abbc472002b5e6dfce47fe9898c6b7d8328d58b5d2524f75e277c07a97eb84"
url: "https://pub.dev"
source: hosted
version: "3.9.0"
permission_handler_windows:
dependency: transitive
description:
name: permission_handler_windows
sha256: f67cab14b4328574938ecea2db3475dad7af7ead6afab6338772c5f88963e38b
url: "https://pub.dev"
source: hosted
version: "0.1.2"
petitparser:
dependency: transitive
description:
Expand Down Expand Up @@ -453,14 +501,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.4"
workmanager:
dependency: "direct main"
description:
name: workmanager
sha256: e0be7e35d644643f164ee45d2ce14414f0e0fdde19456aa66065f35a0b1d2ea1
url: "https://pub.dev"
source: hosted
version: "0.5.1"
xdg_directories:
dependency: transitive
description:
Expand Down
8 changes: 5 additions & 3 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,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: 1.1.0+1
version: 1.2.0+1

environment:
sdk: '>=2.19.6 <3.0.0'
Expand All @@ -39,9 +39,11 @@ dependencies:
intl: ^0.17.0
http: ^0.13.3
# flutter_alarm_clock: ^0.0.2
android_intent_plus: ^3.1.7
workmanager: ^0.5.1
android_intent_plus: ^3.1.8
# workmanager: ^0.5.1
shared_preferences: ^2.1.0
permission_handler: ^10.2.0
android_alarm_manager_plus: ^2.1.3

dev_dependencies:
flutter_test:
Expand Down
3 changes: 3 additions & 0 deletions windows/flutter/generated_plugin_registrant.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

#include "generated_plugin_registrant.h"

#include <permission_handler_windows/permission_handler_windows_plugin.h>

void RegisterPlugins(flutter::PluginRegistry* registry) {
PermissionHandlerWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));
}
1 change: 1 addition & 0 deletions windows/flutter/generated_plugins.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#

list(APPEND FLUTTER_PLUGIN_LIST
permission_handler_windows
)

list(APPEND FLUTTER_FFI_PLUGIN_LIST
Expand Down

0 comments on commit 91dc6e5

Please sign in to comment.