recentsPresses property
One event each time the person presses Recents while this home app is in front and the system shows nothing over it.
Where the system's Recents answers, it covers the app and this stream
stays quiet. Phones whose own launcher hosts Recents can show nothing
when another app is the home app; when the press still reaches the app
as the system's "recentapps" broadcast, the MainActivity
dartvel.android.launcher: true writes tells the app at once (the
dev.dartvel/system_keys channel). A press after which the app is
still in front a moment later went unanswered, and the app can show its
own recent apps. A phone that sends nothing at all for the press (the
button is the system's, not a key the app receives) gives no event:
no app can hear it there. Where no binding is registered the stream is
empty.
Implementation
Stream<void> get recentsPresses {
if (!DVNativeBridge.isRegistered('apps.recentsPressedAt')) return const Stream<void>.empty();
late final StreamController<void> controller;
AppLifecycleListener? listener;
StreamSubscription<DVHomeAppSignal>? keys;
Timer? pending;
int? seen;
int? replacedSeen;
final AppLifecycleState? now = WidgetsBinding.instance.lifecycleState;
bool inFront = now == null || now == AppLifecycleState.resumed;
Future<int> stamp() async {
final Object? value = await DVNativeBridge.invoke<Object?>('apps.recentsPressedAt');
return value is int ? value : 0;
}
void heard(int value) {
if (!inFront || value == 0 || value == seen) return;
seen = value;
// Answered presses cover the app at once; wait to see.
pending?.cancel();
pending = Timer(const Duration(milliseconds: 600), () {
if (inFront && !controller.isClosed) controller.add(null);
});
}
void leave() {
inFront = false;
pending?.cancel();
}
controller = StreamController<void>(
onListen: () {
stamp().then((int value) => seen ??= value);
keys = _DVSystemKeys.heard.listen((DVHomeAppSignal key) {
if (key.name == 'recents') heard(key.at);
// The Recents service already put the app in front, in place of
// the system's Recents: nothing to wait for.
// Kept apart from [seen]: the resume that follows the service's
// new intent reads the same stamp, and may read it first.
if (key.name == 'recentsReplaced' && key.at != replacedSeen && !controller.isClosed) {
replacedSeen = key.at;
pending?.cancel();
controller.add(null);
}
});
listener = AppLifecycleListener(
onInactive: leave,
onHide: leave,
onPause: leave,
onResume: () {
// A press made while covered was answered by what covered it.
stamp().then((int value) {
seen = value;
inFront = true;
});
},
);
},
onCancel: () {
keys?.cancel();
keys = null;
pending?.cancel();
listener?.dispose();
listener = null;
},
);
return controller.stream;
}