Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature -> Add notification tap callback #275

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ class AlarmPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
}
result.success(isRinging)
}
"getLaunchNotification" -> {
val alarmStorage = AlarmStorage(context)
val alarmId = alarmStorage.getAndClearAlarmLaunchId()

result.success(alarmId ?: null)
}
"setWarningNotificationOnKill" -> {
val title = call.argument<String>("title")
val body = call.argument<String>("body")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import io.flutter.Log

class AlarmStorage(context: Context) {
companion object {
private const val PREFS_NAME = "alarm_prefs"
// Prefix shared with the Flutter side to identify alarm settings in shared preferences.
private const val PREFIX = "flutter.__alarm_id__"
}

Expand Down Expand Up @@ -57,4 +57,23 @@ class AlarmStorage(context: Context) {
}
return alarms
}

fun saveAlarmLaunchId(alarmId: Int) {
val editor = prefs.edit()
editor.putInt("launch_alarm_id", alarmId)
editor.apply()
}

fun getAndClearAlarmLaunchId(): Int? {
val key = "launch_alarm_id"
val value = prefs.all[key]
return if (value is Int) {
prefs.edit().remove(key).apply()
value
} else {
// TODO: To remove
Log.e("AlarmStorage", "Expected an Int for key $key but found ${value?.javaClass?.simpleName}")
null
}
}
}
7 changes: 7 additions & 0 deletions example/lib/screens/home.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class _ExampleAlarmHomeScreenState extends State<ExampleAlarmHomeScreen> {

static StreamSubscription<AlarmSettings>? ringSubscription;
static StreamSubscription<int>? updateSubscription;
static StreamSubscription<int>? notificationTapSubscription;

@override
void initState() {
Expand All @@ -36,6 +37,11 @@ class _ExampleAlarmHomeScreenState extends State<ExampleAlarmHomeScreen> {
updateSubscription ??= Alarm.updateStream.stream.listen((_) {
loadAlarms();
});
notificationTapSubscription ??= Alarm.notificationTapStream.stream.listen(
(id) {
alarmPrint('App opened through notification of alarm: $id');
},
);
}

void loadAlarms() {
Expand Down Expand Up @@ -83,6 +89,7 @@ class _ExampleAlarmHomeScreenState extends State<ExampleAlarmHomeScreen> {
void dispose() {
ringSubscription?.cancel();
updateSubscription?.cancel();
notificationTapSubscription?.cancel();
super.dispose();
}

Expand Down
36 changes: 4 additions & 32 deletions example/lib/screens/ring.dart
Original file line number Diff line number Diff line change
@@ -1,39 +1,11 @@
import 'dart:async';

import 'package:alarm/alarm.dart';
import 'package:flutter/material.dart';

class ExampleAlarmRingScreen extends StatefulWidget {
class ExampleAlarmRingScreen extends StatelessWidget {
const ExampleAlarmRingScreen({required this.alarmSettings, super.key});

final AlarmSettings alarmSettings;

@override
State<ExampleAlarmRingScreen> createState() => _ExampleAlarmRingScreenState();
}

class _ExampleAlarmRingScreenState extends State<ExampleAlarmRingScreen> {
@override
void initState() {
super.initState();
Timer.periodic(const Duration(seconds: 1), (timer) async {
if (!mounted) {
timer.cancel();
return;
}

final isRinging = await Alarm.isRinging(widget.alarmSettings.id);
if (isRinging) {
alarmPrint('Alarm ${widget.alarmSettings.id} is still ringing...');
return;
}

alarmPrint('Alarm ${widget.alarmSettings.id} stopped ringing.');
timer.cancel();
if (mounted) Navigator.pop(context);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
Expand All @@ -42,7 +14,7 @@ class _ExampleAlarmRingScreenState extends State<ExampleAlarmRingScreen> {
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
'You alarm (${widget.alarmSettings.id}) is ringing...',
'You alarm (${alarmSettings.id}) is ringing...',
style: Theme.of(context).textTheme.titleLarge,
),
const Text('🔔', style: TextStyle(fontSize: 50)),
Expand All @@ -53,7 +25,7 @@ class _ExampleAlarmRingScreenState extends State<ExampleAlarmRingScreen> {
onPressed: () {
final now = DateTime.now();
Alarm.set(
alarmSettings: widget.alarmSettings.copyWith(
alarmSettings: alarmSettings.copyWith(
dateTime: DateTime(
now.year,
now.month,
Expand All @@ -73,7 +45,7 @@ class _ExampleAlarmRingScreenState extends State<ExampleAlarmRingScreen> {
),
RawMaterialButton(
onPressed: () {
Alarm.stop(widget.alarmSettings.id).then((_) {
Alarm.stop(alarmSettings.id).then((_) {
if (context.mounted) Navigator.pop(context);
});
},
Expand Down
14 changes: 13 additions & 1 deletion ios/Classes/SwiftAlarmPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import AudioToolbox
import MediaPlayer
import BackgroundTasks

public class SwiftAlarmPlugin: NSObject, FlutterPlugin {
public class SwiftAlarmPlugin: NSObject, FlutterPlugin, FlutterApplicationLifeCycleDelegate {
#if targetEnvironment(simulator)
private let isDevice = false
#else
Expand All @@ -24,6 +24,7 @@ public class SwiftAlarmPlugin: NSObject, FlutterPlugin {
instance.channel = channel
instance.registrar = registrar
registrar.addMethodCallDelegate(instance, channel: channel)
registrar.addApplicationDelegate(instance)
}

private var alarms: [Int: AlarmConfiguration] = [:]
Expand All @@ -40,6 +41,14 @@ public class SwiftAlarmPlugin: NSObject, FlutterPlugin {

private var vibratingAlarms: Set<Int> = []

var launchNotification: Int? = nil

func setLaunchNotification(userInfo: [AnyHashable: Any]) {
if let id = userInfo["id"] as? Int {
self.launchNotification = id
}
}

public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "setAlarm":
Expand All @@ -57,6 +66,9 @@ public class SwiftAlarmPlugin: NSObject, FlutterPlugin {
} else {
result(self.alarms[id!]?.audioPlayer?.isPlaying ?? false)
}
case "getLaunchNotification":
result(launchNotification)
launchNotification = nil
case "setWarningNotificationOnKill":
guard let args = call.arguments as? [String: Any] else {
result(FlutterError(code: "NATIVE_ERR", message: "[SwiftAlarmPlugin] Error: Arguments are not in the expected format for setWarningNotificationOnKill", details: nil))
Expand Down
5 changes: 5 additions & 0 deletions ios/Classes/services/NotificationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ class NotificationManager: NSObject, UNUserNotificationCenterDelegate {

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
handleAction(withIdentifier: response.actionIdentifier, for: response.notification)

if let id = response.notification.request.content.userInfo["id"] {
SwiftAlarmPlugin.shared.setLaunchNotification(userInfo: ["id": id])
}

completionHandler()
}

Expand Down
41 changes: 38 additions & 3 deletions lib/alarm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'package:alarm/src/ios_alarm.dart';
import 'package:alarm/utils/alarm_exception.dart';
import 'package:alarm/utils/extensions.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_fgbg/flutter_fgbg.dart';

export 'package:alarm/model/alarm_settings.dart';
export 'package:alarm/model/notification_settings.dart';
Expand All @@ -24,16 +25,23 @@ class Alarm {
/// Whether it's Android device.
static bool get android => defaultTargetPlatform == TargetPlatform.android;

/// Stream subscription to listen to foreground/background events.
static late StreamSubscription<FGBGType> fgbgSubscription;

/// Stream of the alarm updates.
static final updateStream = StreamController<int>();

/// Stream of the ringing status.
static final ringStream = StreamController<AlarmSettings>();

/// Stream of the notification tap.
static final notificationTapStream = StreamController<int>();

/// Initializes Alarm services.
///
/// Also calls [checkAlarm] that will reschedule alarms that were set before
/// app termination.
/// app termination. Also calls [checkOpenOnNotificationTap] to check if the
/// app was brought to foreground by tapping on alarm notification.
///
/// Set [showDebugLogs] to `false` to hide all the logs from the plugin.
static Future<void> init({bool showDebugLogs = true}) async {
Expand All @@ -46,6 +54,19 @@ class Alarm {
await AlarmStorage.init();

await checkAlarm();

fgbgSubscription = FGBGEvents.instance.stream.listen((event) {
if (event == FGBGType.foreground) checkOpenOnNotificationTap();
});
}

/// Checks if the app was opened by tapping on a notification.
static Future<void> checkOpenOnNotificationTap() async {
final id = await Alarm.getLaunchNotification();

if (id == null) return;

notificationTapStream.add(id);
}

/// Checks if some alarms were set on previous session.
Expand Down Expand Up @@ -151,13 +172,18 @@ class Alarm {
}
}

/// Gets the notification id that was used to open the app.
static Future<int?> getLaunchNotification() => iOS
? IOSAlarm.getLaunchNotification()
: AndroidAlarm.getLaunchNotification();

/// Whether the alarm is ringing.
///
/// If no `id` is provided, it checks if any alarm is ringing.
/// If an `id` is provided, it checks if the specific alarm with that `id`
/// is ringing.
static Future<bool> isRinging([int? id]) async =>
iOS ? await IOSAlarm.isRinging(id) : await AndroidAlarm.isRinging(id);
static Future<bool> isRinging([int? id]) =>
iOS ? IOSAlarm.isRinging(id) : AndroidAlarm.isRinging(id);

/// Whether an alarm is set.
static bool hasAlarm() => AlarmStorage.hasAlarm();
Expand All @@ -183,4 +209,13 @@ class Alarm {
await AlarmStorage.prefs.reload();
updateStream.add(id);
}

/// Disposes the alarm resources if they are no longer needed.
static void dispose() {
AlarmStorage.dispose();
fgbgSubscription.cancel();
updateStream.close();
notificationTapStream.close();
ringStream.close();
}
}
5 changes: 5 additions & 0 deletions lib/src/android_alarm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ class AndroidAlarm {
);
}

/// Calls the native function `getLaunchNotification`.
static Future<int?> getLaunchNotification() async {
return methodChannel.invokeMethod<int?>('getLaunchNotification');
}

/// Schedules a native alarm with given [settings] with its notification.
static Future<bool> set(AlarmSettings settings) async {
try {
Expand Down
5 changes: 5 additions & 0 deletions lib/src/ios_alarm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ class IOSAlarm {
if (id != null) await Alarm.reload(id);
}

/// Calls the native function `getLaunchNotification`.
static Future<int?> getLaunchNotification() async {
return methodChannel.invokeMethod<int?>('getLaunchNotification');
}

/// Calls the native function `setAlarm` and listens to alarm ring state.
///
/// Also set periodic timer and listens for app state changes to trigger
Expand Down
Loading