Skip to content

Offline gym log for Android. No account, no ads, no internet.

Add notification sounds from the phone (#310)

InlitX008beb3db849
diff --git a/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt b/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
index 161eb47..ec22fc4 100644
--- a/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
@@ -22,6 +22,7 @@ import java.io.File
import java.io.FileOutputStream
class MainActivity : FlutterActivity() {
+ private var pendingSound: MethodChannel.Result? = null
private var incomingChannel: MethodChannel? = null
private var rotaryChannel: MethodChannel? = null
private var openChannel: MethodChannel? = null
@@ -128,22 +129,97 @@ class MainActivity : FlutterActivity() {
MethodChannel(messenger, "gymmane/device").setMethodCallHandler { call, result ->
when (call.method) {
"isWatch" -> result.success(packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH))
+ "pickSound" -> pickSound(call.argument<String>("current"), result)
"isLowEnd" -> {
val am = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
val info = android.app.ActivityManager.MemoryInfo()
am.getMemoryInfo(info)
result.success(am.isLowRamDevice || info.totalMem < 3_500_000_000L)
}
+ "maxRefresh" -> result.success(maxRefreshRate())
+ "setHighRefresh" -> {
+ setHighRefresh(call.argument<Boolean>("on") ?: false)
+ result.success(null)
+ }
else -> result.notImplemented()
}
}
HealthBridge.attach(this, MethodChannel(messenger, HealthBridge.CHANNEL))
BackupBridge.attach(this, MethodChannel(messenger, BackupBridge.CHANNEL))
+ SoundBridge.attach(this, MethodChannel(messenger, SoundBridge.CHANNEL))
+ VoiceBridge.attach(this, MethodChannel(messenger, VoiceBridge.CHANNEL))
+ }
+
+ private fun currentDisplay(): android.view.Display? =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) display else @Suppress("DEPRECATION") windowManager.defaultDisplay
+
+ private fun maxRefreshRate(): Double {
+ val d = currentDisplay() ?: return 60.0
+ return d.supportedModes.maxOfOrNull { it.refreshRate.toDouble() } ?: d.refreshRate.toDouble()
+ }
+
+ private fun setHighRefresh(on: Boolean) {
+ val d = currentDisplay() ?: return
+ val params = window.attributes
+ if (on) {
+ val now = d.mode
+ val best = d.supportedModes
+ .filter { it.physicalWidth == now.physicalWidth && it.physicalHeight == now.physicalHeight }
+ .maxByOrNull { it.refreshRate } ?: return
+ params.preferredDisplayModeId = best.modeId
+ params.preferredRefreshRate = best.refreshRate
+ } else {
+ params.preferredDisplayModeId = 0
+ params.preferredRefreshRate = 0f
+ }
+ window.attributes = params
}
@Deprecated("Deprecated in Java")
+ private fun pickSound(current: String?, result: MethodChannel.Result) {
+ pendingSound?.success(null)
+ pendingSound = result
+ val intent = Intent(android.media.RingtoneManager.ACTION_RINGTONE_PICKER).apply {
+ putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_TYPE, android.media.RingtoneManager.TYPE_NOTIFICATION)
+ putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false)
+ putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false)
+ if (!current.isNullOrEmpty()) {
+ putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(current))
+ }
+ }
+ try {
+ startActivityForResult(intent, SOUND_REQUEST)
+ } catch (_: Exception) {
+ pendingSound = null
+ result.success(null)
+ }
+ }
+
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ if (requestCode == SOUND_REQUEST) {
+ val result = pendingSound
+ pendingSound = null
+ val uri: Uri? = if (resultCode == RESULT_OK && data != null) {
+ if (Build.VERSION.SDK_INT >= 33) {
+ data.getParcelableExtra(android.media.RingtoneManager.EXTRA_RINGTONE_PICKED_URI, Uri::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ data.getParcelableExtra(android.media.RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
+ }
+ } else null
+ if (uri == null) {
+ result?.success(null)
+ } else {
+ val name = try {
+ android.media.RingtoneManager.getRingtone(this, uri)?.getTitle(this)
+ } catch (_: Exception) {
+ null
+ }
+ result?.success(mapOf("uri" to uri.toString(), "name" to (name ?: "")))
+ }
+ return
+ }
if (BackupBridge.onActivityResult(this, requestCode, resultCode, data)) return
super.onActivityResult(requestCode, resultCode, data)
}
@@ -274,4 +350,8 @@ class MainActivity : FlutterActivity() {
MediaStore.Images.Media.insertImage(contentResolver, file.absolutePath, name, null)
return true
}
+
+ companion object {
+ private const val SOUND_REQUEST = 7311
+ }
}
diff --git a/android/app/src/main/kotlin/com/gymmane/app/SoundBridge.kt b/android/app/src/main/kotlin/com/gymmane/app/SoundBridge.kt
new file mode 100644
index 0000000..913d18d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/gymmane/app/SoundBridge.kt
@@ -0,0 +1,84 @@
+package com.gymmane.app
+
+import android.content.ContentUris
+import android.content.Context
+import android.media.AudioAttributes
+import android.media.Ringtone
+import android.media.RingtoneManager
+import android.net.Uri
+import android.provider.MediaStore
+import io.flutter.plugin.common.MethodChannel
+
+object SoundBridge {
+ const val CHANNEL = "gymmane/sounds"
+ private var playing: Ringtone? = null
+
+ fun attach(context: Context, channel: MethodChannel) {
+ channel.setMethodCallHandler { call, result ->
+ when (call.method) {
+ "list" -> result.success(list(context))
+ "play" -> {
+ play(context, call.argument<String>("uri"))
+ result.success(true)
+ }
+ "stop" -> {
+ stop()
+ result.success(true)
+ }
+ else -> result.notImplemented()
+ }
+ }
+ }
+
+ fun detach() = stop()
+
+ private fun list(context: Context): List<Map<String, String>> {
+ val base = MediaStore.Audio.Media.INTERNAL_CONTENT_URI
+ val sounds = mutableListOf<Map<String, String>>()
+ try {
+ context.contentResolver.query(
+ base,
+ arrayOf(MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE),
+ "${MediaStore.Audio.Media.IS_NOTIFICATION} != 0",
+ null,
+ "${MediaStore.Audio.Media.TITLE} COLLATE NOCASE",
+ )?.use { cursor ->
+ while (cursor.moveToNext()) {
+ val title = cursor.getString(1) ?: continue
+ val uri = ContentUris.withAppendedId(base, cursor.getLong(0))
+ sounds += mapOf("title" to title, "uri" to uri.toString())
+ }
+ }
+ } catch (_: Exception) {
+ }
+ return sounds.distinctBy { it["title"] }
+ }
+
+ private fun play(context: Context, uri: String?) {
+ stop()
+ val target = if (uri.isNullOrEmpty()) {
+ RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
+ } else {
+ Uri.parse(uri)
+ }
+ playing = try {
+ RingtoneManager.getRingtone(context, target)?.apply {
+ audioAttributes = AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_NOTIFICATION)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
+ .build()
+ play()
+ }
+ } catch (_: Exception) {
+ null
+ }
+ }
+
+ private fun stop() {
+ try {
+ playing?.stop()
+ } catch (_: Exception) {
+ }
+ playing = null
+ }
+}
diff --git a/lib/services/notif_sound.dart b/lib/services/notif_sound.dart
new file mode 100644
index 0000000..23b6166
--- /dev/null
+++ b/lib/services/notif_sound.dart
@@ -0,0 +1,93 @@
+import 'dart:io' show Platform;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+
+enum SoundGroup { train, food, other }
+
+class NotifSound {
+ NotifSound._();
+
+ static const silent = 'silent';
+ static const _channel = MethodChannel('gymmane/device');
+
+ static final Map<SoundGroup, String> uris = {};
+
+ static String uriOf(SoundGroup g) => uris[g] ?? '';
+
+ static bool plays(SoundGroup g) => uriOf(g) != silent;
+
+ static AndroidNotificationSound? soundOf(SoundGroup g) {
+ final u = uriOf(g);
+ return u.isEmpty || u == silent ? null : UriAndroidNotificationSound(u);
+ }
+
+ static String channelOf(String base, SoundGroup g) {
+ final u = uriOf(g);
+ if (u.isEmpty) return base;
+ if (u == silent) return '${base}_silent';
+ var h = 0x811c9dc5;
+ for (final c in u.codeUnits) {
+ h = ((h ^ c) * 0x01000193) & 0xffffffff;
+ }
+ return '${base}_${h.toRadixString(36)}';
+ }
+
+ static Future<({String uri, String name})?> pick(String current) async {
+ if (kIsWeb || !Platform.isAndroid) return null;
+ try {
+ final r = await _channel.invokeMapMethod<String, String>('pickSound', {'current': current});
+ final uri = r?['uri'] ?? '';
+ if (uri.isEmpty) return null;
+ return (uri: uri, name: r?['name'] ?? '');
+ } catch (_) {
+ return null;
+ }
+ }
+
+ static const _sounds = MethodChannel('gymmane/sounds');
+ static List<({String uri, String name})>? _list;
+
+ static Future<List<({String uri, String name})>> phoneSounds() async {
+ if (_list case final cached?) return cached;
+ if (kIsWeb || !Platform.isAndroid) return const [];
+ try {
+ final raw = await _sounds.invokeListMethod<Map>('list') ?? const [];
+ return _list = [
+ for (final m in raw) (uri: '${m['uri'] ?? ''}', name: '${m['title'] ?? ''}'),
+ ];
+ } catch (_) {
+ return const [];
+ }
+ }
+
+ static Future<void> preview(String uri) async {
+ if (kIsWeb || !Platform.isAndroid) return;
+ try {
+ await _sounds.invokeMethod('play', {'uri': uri});
+ } catch (_) {}
+ }
+
+ static Future<void> stopPreview() async {
+ if (kIsWeb || !Platform.isAndroid) return;
+ try {
+ await _sounds.invokeMethod('stop');
+ } catch (_) {}
+ }
+
+ static Future<void> dropOld(List<String> bases, Set<String> keep) async {
+ if (kIsWeb || !Platform.isAndroid) return;
+ try {
+ final android = FlutterLocalNotificationsPlugin()
+ .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
+ final channels = await android?.getNotificationChannels() ?? const [];
+ for (final c in channels) {
+ if (keep.contains(c.id)) continue;
+ if (bases.any((b) => c.id == b || c.id.startsWith('${b}_'))) {
+ await android?.deleteNotificationChannel(channelId: c.id);
+ }
+ }
+ } catch (_) {}
+ }
+}
diff --git a/lib/services/progress_reminder.dart b/lib/services/progress_reminder.dart
index 3e4d485..336ff15 100644
--- a/lib/services/progress_reminder.dart
+++ b/lib/services/progress_reminder.dart
@@ -3,6 +3,7 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import '../l10n/l10n.dart';
+import 'notif_sound.dart';
import 'train_reminder.dart';
class ProgressReminder {
@@ -16,12 +17,13 @@ class ProgressReminder {
bool enabled = true;
AndroidNotificationDetails get _android => AndroidNotificationDetails(
- 'progress_photo',
+ NotifSound.channelOf('progress_photo', SoundGroup.other),
t.notifPhotoChannel,
channelDescription: t.notifPhotoChannelWhy,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
- playSound: true,
+ playSound: NotifSound.plays(SoundGroup.other),
+ sound: NotifSound.soundOf(SoundGroup.other),
);
DarwinNotificationDetails get _darwin => const DarwinNotificationDetails(
@@ -66,12 +68,13 @@ class ProgressReminder {
scheduledDate: when,
notificationDetails: NotificationDetails(
android: AndroidNotificationDetails(
- 'measures',
+ NotifSound.channelOf('measures', SoundGroup.other),
t.notifMeasureChannel,
channelDescription: t.notifMeasureChannelWhy,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
- playSound: true,
+ playSound: NotifSound.plays(SoundGroup.other),
+ sound: NotifSound.soundOf(SoundGroup.other),
),
iOS: _darwin,
),
@@ -86,12 +89,13 @@ class ProgressReminder {
static const _fastDoneId = 1005;
AndroidNotificationDetails _fastAndroid({required bool live, DateTime? end}) => AndroidNotificationDetails(
- live ? 'fasting_live' : 'fasting',
+ live ? 'fasting_live' : NotifSound.channelOf('fasting', SoundGroup.food),
live ? t.notifFastLiveChannel : t.notifFastChannel,
channelDescription: live ? t.notifFastLiveChannelWhy : t.notifFastChannelWhy,
importance: live ? Importance.low : Importance.defaultImportance,
priority: live ? Priority.low : Priority.defaultPriority,
- playSound: !live,
+ playSound: !live && NotifSound.plays(SoundGroup.food),
+ sound: live ? null : NotifSound.soundOf(SoundGroup.food),
enableVibration: !live,
ongoing: live,
autoCancel: !live,
diff --git a/lib/services/supplement_reminder.dart b/lib/services/supplement_reminder.dart
index bfccf31..f898157 100644
--- a/lib/services/supplement_reminder.dart
+++ b/lib/services/supplement_reminder.dart
@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../l10n/l10n.dart';
+import 'notif_sound.dart';
import 'train_reminder.dart';
class SupplementReminder {
@@ -19,12 +20,13 @@ class SupplementReminder {
_queue = _queue.then((_) => job()).catchError((Object e) => debugPrint('Aviso de suplementos: $e'));
AndroidNotificationDetails get _android => AndroidNotificationDetails(
- 'supplement_reminder',
+ NotifSound.channelOf('supplement_reminder', SoundGroup.food),
t.notifSuppChannel,
channelDescription: t.notifSuppChannelWhy,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
- playSound: true,
+ playSound: NotifSound.plays(SoundGroup.food),
+ sound: NotifSound.soundOf(SoundGroup.food),
);
DarwinNotificationDetails get _darwin => const DarwinNotificationDetails(
diff --git a/lib/services/train_reminder.dart b/lib/services/train_reminder.dart
index 4bc77fb..2d31324 100644
--- a/lib/services/train_reminder.dart
+++ b/lib/services/train_reminder.dart
@@ -3,6 +3,7 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import '../l10n/l10n.dart';
+import 'notif_sound.dart';
class TrainReminder {
TrainReminder._();
@@ -21,12 +22,13 @@ class TrainReminder {
_queue = _queue.then((_) => job()).catchError((Object e) => debugPrint('Aviso de entreno: $e'));
AndroidNotificationDetails get _android => AndroidNotificationDetails(
- 'train_reminder',
+ NotifSound.channelOf('train_reminder', SoundGroup.train),
t.notifTrainChannel,
channelDescription: t.notifTrainChannelWhy,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
- playSound: true,
+ playSound: NotifSound.plays(SoundGroup.train),
+ sound: NotifSound.soundOf(SoundGroup.train),
);
DarwinNotificationDetails get _darwin => const DarwinNotificationDetails(