199 Commits

Author SHA1 Message Date
Michatec 255f27bddf perf(dsp): optimize equalizer and update coefficients calculation 2026-04-08 11:48:56 +02:00
Michatec 45576e1577 refactor(player): remove eighth equalizer band preference 2026-04-08 11:08:41 +02:00
Michatec 1212fc61b5 fix(equalizer): update band mappings and reset all bands 2026-04-08 11:04:12 +02:00
Michatec cdf7668d43 refactor(dsp): improve reverb algorithm and update audio presets 2026-04-07 16:10:50 +02:00
Michatec f755dc5173 perf(dsp): optimize audio processing and atomic memory ordering 2026-04-07 15:55:16 +02:00
Michatec 8c7a8ce7c4 feat(ui): add dedicated station search fragment for television platforms 2026-04-07 12:59:33 +02:00
Michatec d1cc340417 feat(ui): add visualizer button to collection screen 2026-04-07 11:58:23 +02:00
Michatec e0d1770a19 feat(dsp): refine audio processing and visualizer rendering 2026-04-07 11:26:14 +02:00
Michachatz 2e8cc9b243 refactor(helpers): adjust the bass boost value 2026-04-07 01:09:13 +02:00
Michatec 9e1219549e docs(readme): add Cast to Devices support to the Android TV section 2026-04-06 23:33:25 +02:00
Michatec 17ba1c268a refactor(gradle): relocate ndkVersion to top-level build script 2026-04-06 23:21:45 +02:00
Michatec b328af5c3a build(gradle): set ndk version 29.0.14206865 in gradle build and ci workflow 2026-04-06 23:20:06 +02:00
Michatec d31d476cb5 ci: add ZIPALIGN env variable to gradle-publish workflow 2026-04-06 23:15:54 +02:00
Michatec 6bb34cd707 chore(config): add .vscode configuration folder 2026-04-06 23:11:30 +02:00
Michatec 883a4443e9 refactor(dsp): make DSP thread‑safe and add EQ interpolation 2026-04-06 22:58:45 +02:00
Michatec 8ba22a4c09 feat(audio): add runtime sample rate handling and thread safety 2026-04-06 22:44:57 +02:00
Michatec 9d47684f13 feat(ui): add television layouts and improve visualizer performance 2026-04-06 17:17:29 +02:00
Michatec 82993d7c97 feat(ui): add spectrum analyzer visualizer 2026-04-06 16:58:53 +02:00
Michatec 487195b716 build: rename target library to dsp in CMakeLists.txt 2026-04-06 15:20:20 +02:00
Michatec 12445a3918 build: rename native audio library from radio to dsp 2026-04-06 15:16:41 +02:00
Michatec bc38742eae perf(audio): adjust audio processing presets and limiters 2026-04-06 15:14:01 +02:00
Michatec 99499ad174 perf(audio): optimize signal processing with NEON and block-based gains 2026-04-06 14:29:08 +02:00
Michatec 0d35770375 feat(audio): add 10-band equalizer and audio presets 2026-04-06 13:27:53 +02:00
Michatec 0d0980a1ef refactor(radio): change Reverb indices to size_t 2026-04-05 19:14:57 +02:00
Michachatz ae215691ca Update radio.cpp 2026-04-05 19:09:43 +02:00
Michachatz 52f1a57de3 Update radio.cpp 2026-04-05 19:07:27 +02:00
Michatec 53abe918ca fix(player): improve cast player integration and service lifecycle management 2026-04-05 18:19:00 +02:00
Michatec bd3ad427fa ui(settings): move app version to top of preference screen 2026-04-05 17:24:39 +02:00
Michatec 7b2cfb4b17 feat(cast): implement Google Cast support and expanded controller activity 2026-04-05 17:15:48 +02:00
Michatec 0796bc8ef4 build(deps): bump version to 14.5 and update cast framework dependency 2026-04-05 14:47:51 +02:00
Michatec 1564fa3dc4 feat(audio): add native audio processing and Google Cast support 2026-04-05 14:38:05 +02:00
Michatec d40ae6b746 feat(audio): add native audio processing and Google Cast support 2026-04-05 14:01:47 +02:00
Michatec d270574365 refactor(helpers): minor code cleanup and documentation fixes 2026-03-30 15:37:35 +02:00
Michatec f96bdc6f07 style(ui): hide loading layout directly 2026-03-30 12:01:37 +02:00
Michatec 7d63f16c2c chore: cleanup AppThemeHelper and add loading string 2026-03-30 11:34:16 +02:00
Michatec 47ff40e676 style(ui): remove navigation bar color overrides and redundant v27 styles 2026-03-30 11:12:21 +02:00
Michatec dad709f5df feat(ui): implement edge-to-edge support and improve splash transition
- Enable edge-to-edge display in `MainActivity` and handle window insets in `PlayerFragment`.
- Add a fade-out animation when hiding the loading overlay.
- Sync player state with the controller during setup and reset playing state in preferences on service destruction.
- Simplify splash screen drawable and update background color attributes in layout.
- Remove manual navigation bar color overrides.
2026-03-30 11:06:41 +02:00
Michatec 89b13e152c refactor(ui): improve intent handling and collection view state
- Update `handleStartIntent` and `handleStartPlayer` in `PlayerFragment` to ensure intents are only cleared if successfully handled and stations are valid.
- Refine star icon rendering in `CollectionAdapter` by clearing color filters when appropriate.
- Remove obsolete commented-out code and update log messages in `PlayerFragment`, `PlayerService`, and `LayoutHolder`.
- Uncomment maintenance preference updates in `SettingsFragment`.
- Reformat code for better readability in `CollectionAdapter`.
2026-03-30 10:22:05 +02:00
Michatec 1eefe1acc4 Merge remote-tracking branch 'origin/main' 2026-03-30 09:18:34 +02:00
Michatec 1fa8102e1c feat(ui): implement station reordering via DPAD for TV navigation 2026-03-30 09:18:15 +02:00
Michachatz c057aaaf2f Remove license badge from README
Removed license badge from README.
2026-03-30 00:21:43 +02:00
Michatec 067177bd79 docs(readme): enhance credit attribution section 2026-03-30 00:15:52 +02:00
Michatec 866dba6d3b docs(readme): simplify credit attribution 2026-03-30 00:14:27 +02:00
Michatec 51c42dc6f1 style(license): fix formatting in GPLv3 license file 2026-03-30 00:13:04 +02:00
Michatec 827f709450 chore(license): change project license from MIT to GPLv3 2026-03-30 00:11:37 +02:00
Michatec 04866cfa35 docs(readme): add project badges to header 2026-03-29 23:53:49 +02:00
Michatec 3171c21db9 style(ui): make television dialogs responsive 2026-03-28 23:11:42 +01:00
Michatec f43775d3f2 style(ui): adjust television dialog heights to 800dp 2026-03-28 23:05:53 +01:00
Michatec 868c39a6e1 style(ui): increase find station dialog height 2026-03-28 22:59:25 +01:00
Michatec 985e7d4e1b style(ui): increase find station dialog height 2026-03-28 22:53:00 +01:00
Michatec 363d197ba5 style(ui): simplify theme selection dialog radio buttons 2026-03-28 22:47:13 +01:00
Michatec d0e412ca83 feat(ui): save theme selection to preferences 2026-03-28 22:37:55 +01:00
Michatec 93008f7247 feat(ui): handle theme selection dialog results and update summary 2026-03-28 22:29:02 +01:00
Michatec 7e95a0bfe1 refactor(ui): unify theme selection by removing TV-specific handling 2026-03-28 22:21:38 +01:00
Michatec 8d509b6b23 refactor(ui): update theme selection dialog behavior and TV layout 2026-03-28 22:18:12 +01:00
Michatec cb4aff47a7 feat(ui): add theme selection dialog layout 2026-03-28 22:01:33 +01:00
Michatec 293a823442 fix(ui): ensure theme selection dialog dismisses on button click 2026-03-28 21:58:24 +01:00
Michatec a5b11ba99a feat(ui): implement theme selection dialog with TV support 2026-03-28 21:55:38 +01:00
Michatec 2ccb4225d4 refactor(ui): remove TV-specific preference layouts 2026-03-28 21:39:05 +01:00
Michatec 453e6e5b71 refactor(ui): adjust TV preference layout structure 2026-03-28 21:30:02 +01:00
Michatec 4108cf2c7c feat(ui): add TV-specific preference layouts for focus visibility 2026-03-28 21:25:50 +01:00
Michatec f038e01981 feat(ui): add keyboard shortcut for favouriting stations 2026-03-28 21:03:54 +01:00
Michatec f66b5af810 docs(readme): add DEL key alternative for station removal 2026-03-28 20:56:08 +01:00
Michatec a6a9daf3a3 docs(readme): add Android TV controls documentation 2026-03-28 20:54:56 +01:00
Michatec d79d5e15fa refactor(ui): consolidate keyboard shortcut handling in collection adapter 2026-03-28 20:48:54 +01:00
Michatec c3f37092de feat(ui): add keyboard shortcuts for station removal 2026-03-28 20:34:56 +01:00
Michatec 48d14fecdb style(ui): adjust highlight colors for better contrast
Reduce opacity of focused highlight colors and adjust control highlight colors across all theme variants to improve visual consistency and accessibility. Changes include:
- Lowering alpha values for focused highlights in night themes
- Switching from white-based to black-based highlights in light themes
- Standardizing highlight opacity across API level-specific styles
2026-03-28 20:10:41 +01:00
Michatec c8293b1b6d - standardize highlight colors across themes 2026-03-28 19:38:28 +01:00
Michatec 51c8d5b303 Add rotation animation to playback button for mobile devices 2026-03-28 19:02:38 +01:00
Michatec 180d5c2218 Set enabled state for stream URI editing preference 2026-03-28 18:55:19 +01:00
Michatec 391999c406 Update README to mention Android TV support 2026-03-28 18:40:13 +01:00
Michatec fb779bd661 Merge remote-tracking branch 'origin/main' 2026-03-28 18:37:07 +01:00
Michatec 46ebf21c06 Add support for Android TV and update dependencies
*   Implement initial Android TV support, including `LEANBACK_LAUNCHER` intent filter, hardware feature declarations, and television-specific layouts for the player, search results, and dialogs.
*   Add a splash/loading screen for the TV interface and a dedicated `SplashTheme`.
*   Improve DPAD navigation by adding `OnKeyListener` for station cards and allowing focus on internal elements.
*   Update `LayoutHolder` and `PlayerFragment` to handle TV layouts and add previous/next station navigation buttons.
*   Adjust `PreferencesHelper` to disable station editing by default on TV devices.
*   Update `androidx.media3` to v1.10.0, `work-runtime-ktx` to v2.11.2, and add `androidx.leanback` dependency.
*   Bump `versionCode` to 144 and `versionName` to 14.4.
*   Refactor `PlayerService` to simplify sleep timer cancellation logic.
*   Remove stale copyright headers and license comments from several Kotlin files.
2026-03-28 18:36:50 +01:00
Michachatz 2d2d95875f Merge pull request #60 from Michatec/renovate/media3
Update media3 to v1.10.0
2026-03-27 14:12:16 +01:00
renovate[bot] 46e7b905c8 Update media3 to v1.10.0 2026-03-27 12:45:39 +00:00
Michachatz d033ae6344 Merge pull request #59 from Michatec/renovate/workruntimektx
Update dependency androidx.work:work-runtime-ktx to v2.11.2
2026-03-27 13:45:08 +01:00
renovate[bot] fc275d349b Update dependency androidx.work:work-runtime-ktx to v2.11.2 2026-03-25 20:25:14 +00:00
Michachatz 4e6f7c7c67 Update gradle-publish.yml to target main branch
Restrict workflow triggers to main branch for push and pull requests.
2026-03-25 07:52:12 +01:00
Michachatz 272d6fd908 Add installation instructions for Radio 2026-03-25 07:36:28 +01:00
Michachatz 4a30828c99 Update README with warning about Google requirements
Added a warning about Google's upcoming requirement for personal identity details for apps on certified Android devices, effective 2026/2027.
2026-03-25 07:35:21 +01:00
Michachatz 963f6e7618 Merge pull request #58 from Michatec/renovate/android-actions-setup-android-4.x
Update android-actions/setup-android action to v4
2026-03-25 07:30:33 +01:00
renovate[bot] 29ead7e1d8 Update android-actions/setup-android action to v4 2026-03-25 01:58:58 +00:00
Michatec 9140b54a23 Update AndroidManifest to resolve App Link verification issues
- Update `tools:targetApi` from "tiramisu" to "33"
- Set `android:autoVerify="false"` for the MIME-type based intent-filter
- Add `tools:ignore="AppLinkUrlError"` to the wildcard host in the file-extension intent-filter
- Add comments clarifying App Link behavior for playlist links
2026-03-24 17:54:48 +01:00
Michatec 57c4075f19 - Updated .gitignore 2026-03-24 12:40:25 +01:00
Michatec 5334b88f1d Refactor code and clean up unused resources
- Replace `suspendCoroutine` with `suspendCancellableCoroutine` in helper classes for better cancellation support.
- Replace `bundleOf` with manual `Bundle` initialization in `MediaControllerExt` and `SettingsFragment`.
- Remove unused constants in `Keys.kt` and redundant `onTerminate` override in `Radio.kt`.
- Clean up syntax and remove semicolons in `MainActivity.kt`.
2026-03-24 12:36:04 +01:00
Michatec 5978aab0aa - New Version Released.
- Updated the Gradle Structure.
- libs.versions.toml added.
2026-03-24 12:28:15 +01:00
Michachatz c3c2ccfdd9 Add FreeDroidWarn import to MainActivity 2026-03-24 08:04:30 +01:00
Michachatz 38fb4d162b Change Maven repository URL from jetpack.io to jitpack.io 2026-03-24 08:00:10 +01:00
Michachatz 3c3c18104b Fix case sensitivity in FreeDroidWarn dependency 2026-03-24 07:58:25 +01:00
Michachatz 4e1ee7d6a7 Fix version tag format for FreeDroidWarn dependency 2026-03-24 07:56:42 +01:00
Michachatz 64ba020eae Update FreeDroidWarn dependency version to 1.10 2026-03-24 07:52:22 +01:00
Michachatz b35d7bd67c Add JitPack and Jetpack repositories to settings 2026-03-24 07:48:05 +01:00
Michachatz d3dd098639 Remove unused repositories block in build.gradle
Removed unused repositories block from allprojects.
2026-03-24 07:45:59 +01:00
Michachatz a8f6c7f946 Re-add allprojects block with repositories configuration 2026-03-24 07:43:30 +01:00
Michachatz 765ccc9250 Add JitPack repository configuration
Add JitPack repository to all projects.
2026-03-24 07:41:22 +01:00
Michachatz c9d6cf27ec Show warning on upgrade in MainActivity 2026-03-24 07:37:04 +01:00
Michachatz 7b7579d416 Add FreeDroidWarn library dependency 2026-03-24 07:34:09 +01:00
Michachatz d452d7f7ee Merge pull request #57 from Michatec/renovate/gradle-9.x
Update Gradle to v9.4.1
2026-03-19 17:34:25 +01:00
renovate[bot] 2bb3d22cab Update Gradle to v9.4.1 2026-03-19 09:40:18 +00:00
Michachatz b4ed3e107c Merge pull request #53 from Michatec/renovate/androidx.media3-media3-datasource-okhttp-1.x
Update dependency androidx.media3:media3-datasource-okhttp to v1.9.3
2026-03-17 08:09:16 +01:00
Michachatz ef843b601a Merge pull request #54 from Michatec/renovate/androidx.media3-media3-exoplayer-1.x
Update dependency androidx.media3:media3-exoplayer to v1.9.3
2026-03-17 08:09:05 +01:00
renovate[bot] 219d54f4e4 Update dependency androidx.media3:media3-exoplayer to v1.9.3 2026-03-17 07:08:20 +00:00
Michachatz c8a39bf2d7 Merge pull request #55 from Michatec/renovate/androidx.media3-media3-exoplayer-hls-1.x
Update dependency androidx.media3:media3-exoplayer-hls to v1.9.3
2026-03-17 08:07:59 +01:00
renovate[bot] 81ff920c2c Update dependency androidx.media3:media3-exoplayer-hls to v1.9.3 2026-03-17 07:07:36 +00:00
renovate[bot] f4a5209e14 Update dependency androidx.media3:media3-datasource-okhttp to v1.9.3 2026-03-17 07:07:33 +00:00
Michachatz c7b7bdcbed Merge pull request #56 from Michatec/renovate/androidx.media3-media3-session-1.x
Update dependency androidx.media3:media3-session to v1.9.3
2026-03-17 08:07:10 +01:00
Michachatz eae9176f21 Merge pull request #52 from Michatec/renovate/kotlin-monorepo
Update plugin org.jetbrains.kotlin.android to v2.3.20
2026-03-17 08:06:54 +01:00
renovate[bot] b3a833fa44 Update dependency androidx.media3:media3-session to v1.9.3 2026-03-16 20:52:12 +00:00
renovate[bot] 35a8ed46ff Update plugin org.jetbrains.kotlin.android to v2.3.20 2026-03-16 09:20:44 +00:00
Michachatz fd18943878 Change copyright year to 2026
Update copyright year in the LICENSE file.
2026-03-13 06:30:07 +01:00
Michachatz 094fb508e2 Merge pull request #51 from Michatec/renovate/androidx.core-core-ktx-1.x
Update dependency androidx.core:core-ktx to v1.18.0
2026-03-13 06:28:00 +01:00
renovate[bot] 874cf1eb39 Update dependency androidx.core:core-ktx to v1.18.0 2026-03-13 05:26:26 +00:00
Michachatz 211cb387ad Merge pull request #50 from Michatec/renovate/androidx.activity-activity-ktx-1.x
Update dependency androidx.activity:activity-ktx to v1.13.0
2026-03-13 06:25:57 +01:00
renovate[bot] 5481a06343 Update dependency androidx.activity:activity-ktx to v1.13.0 2026-03-11 18:10:24 +00:00
Michatec fbafcb9773 - New Version Released
- Updated MainActivity.kt
2026-03-08 16:03:28 +01:00
Michatec 27c405fd58 - Added Daemon Update
- Updated Icons in PlayerService.kt
2026-03-08 15:45:03 +01:00
Michachatz c2cba26c66 Merge pull request #49 from Michatec/renovate/gradle-9.x
Update Gradle to v9.4.0
2026-03-04 21:15:21 +01:00
renovate[bot] 9224e45b18 Update Gradle to v9.4.0 2026-03-04 13:05:49 +00:00
Michachatz 90164d7e6a Merge pull request #48 from Michatec/renovate/com.android.library-9.x
Update plugin com.android.library to v9.1.0
2026-03-04 07:36:28 +01:00
renovate[bot] 45e208e7a9 Update plugin com.android.library to v9.1.0 2026-03-04 06:35:34 +00:00
Michachatz 1d040e3edc Merge pull request #47 from Michatec/renovate/com.android.application-9.x
Update plugin com.android.application to v9.1.0
2026-03-04 07:35:02 +01:00
renovate[bot] efe17bc82b Update plugin com.android.application to v9.1.0 2026-03-03 16:37:22 +00:00
Michachatz 8b06309c64 Merge pull request #46 from Michatec/renovate/major-github-artifact-actions
Update actions/upload-artifact action to v7
2026-02-27 09:41:56 +01:00
Michatec 669fd4683c - Release of 14.1
- Added new features
- Some bug fixes
2026-02-27 09:40:59 +01:00
Michatec 26b155a721 - Added the Station update button to the SettingsFragment.kt
- Added the strings for the language: german and english
2026-02-27 08:59:04 +01:00
renovate[bot] 99f7863749 Update actions/upload-artifact action to v7 2026-02-26 21:01:43 +00:00
Michachatz 008170811a Update issue templates 2026-02-24 16:26:38 +01:00
Michachatz c0072fe54f Aktualisieren von gradle-publish.yml 2026-02-24 16:23:14 +01:00
Michatec c62c61f2f1 - Removed some old Systems
- Removed some old functions
2026-02-24 14:55:21 +01:00
Michatec 5ca2b9b7ef - Some Bug fixes
- Remove Code berg icon
- Updated README.md
- Updated AndroidManifest.xml
- Updated Dependencies
- Fix some code
2026-02-24 14:46:03 +01:00
Michatec 9b5c7e3c04 - New version Initialized 2026-01-25 17:07:30 +01:00
Michatec 4466654e92 - Fix unused import 2026-01-25 16:33:45 +01:00
Michatec b2de7bd534 - Progress Bar added
- CollectionAdapter.kt updated
- File download optimized
- Housekeeping updated
2026-01-25 16:33:17 +01:00
Michatec d3dfcb98f9 - Layout Changes
- HLS media extraction
2026-01-25 16:08:22 +01:00
Michachatz 0adb906438 Aktualisieren von provider_paths.xml 2026-01-22 06:55:40 +01:00
Michachatz 49e63d3aaa Aktualisieren von shortcuts.xml 2026-01-22 06:55:08 +01:00
Michatec f892a137ce - Fix .yml 2026-01-21 18:14:38 +01:00
Michatec 364ef3db5d - Fix window over resize. 2026-01-21 17:47:47 +01:00
Michachatz e22a5463bd Update APK path in gradle-publish workflow 2026-01-21 17:39:09 +01:00
Michatec 51b37d8f7b - Fixing some bug fixes. 2026-01-21 17:10:35 +01:00
Michatec 5412f59f61 - New Version Initialized
- Some deprecated fixes
- New functions and fallbacks
- Some bug fixes
2026-01-21 16:25:37 +01:00
Michachatz 032728626e Merge pull request #26 from Michatec/renovate/com.android.application-9.x
Update plugin com.android.application to v9
2026-01-21 06:50:14 +01:00
renovate[bot] 1daa762c07 Update plugin com.android.application to v9 2026-01-21 05:49:12 +00:00
Michachatz bcc8af8e57 Merge pull request #27 from Michatec/renovate/com.android.library-9.x
Update plugin com.android.library to v9
2026-01-21 06:48:44 +01:00
Michachatz c045c03524 Merge pull request #28 from Michatec/renovate/gradle-9.x
Update Gradle to v9.3.0
2026-01-21 06:48:34 +01:00
renovate[bot] 6e32b17b94 Update Gradle to v9.3.0 2026-01-16 15:34:20 +00:00
renovate[bot] 81427d3853 Update plugin com.android.library to v9 2026-01-15 18:52:39 +00:00
Michachatz 9b6b1afa68 Update gradle-publish.yml 2025-12-19 12:34:55 +01:00
Michachatz cc631c14c4 Update renovate.json 2025-12-19 12:32:57 +01:00
Michachatz eb55746a2e Merge pull request #25 from Michatec/renovate/gradle-9.x
Update Gradle to v9
2025-12-19 12:29:47 +01:00
renovate[bot] 026b4936f5 Update Gradle to v9 2025-12-19 11:29:13 +00:00
Michachatz 1719b3079c Merge pull request #24 from Michatec/renovate/com.android.library-8.x
Update plugin com.android.library to v8.13.2
2025-12-19 12:26:50 +01:00
renovate[bot] 89f08f284d Update plugin com.android.library to v8.13.2 2025-12-19 11:26:34 +00:00
Michachatz ba34829de0 Merge pull request #17 from Michatec/renovate/com.android.library-8.x
Update plugin com.android.library to v8.13.2
2025-12-19 12:21:19 +01:00
Michachatz d797c07656 Merge branch 'main' into renovate/com.android.library-8.x 2025-12-19 12:20:53 +01:00
Michachatz f9114ebfc9 Merge pull request #16 from Michatec/renovate/com.android.application-8.x
Update plugin com.android.application to v8.13.2
2025-12-19 12:19:40 +01:00
Michachatz 7781868c38 Merge pull request #11 from Michatec/renovate/androidx.media3-media3-exoplayer-hls-1.x
Update dependency androidx.media3:media3-exoplayer-hls to v1.9.0
2025-12-19 12:19:25 +01:00
Michachatz c9c303df6e Merge pull request #9 from Michatec/renovate/androidx.media3-media3-datasource-okhttp-1.x
Update dependency androidx.media3:media3-datasource-okhttp to v1.9.0
2025-12-19 12:19:11 +01:00
Michachatz 34971d4ea4 Merge pull request #6 from Michatec/renovate/androidx.navigation-navigation-ui-ktx-2.x
Update dependency androidx.navigation:navigation-ui-ktx to v2.9.6
2025-12-19 12:18:57 +01:00
Michachatz aa86fee1df Merge pull request #7 from Michatec/renovate/com.google.code.gson-gson-2.x
Update dependency com.google.code.gson:gson to v2.13.2
2025-12-19 12:18:42 +01:00
Michachatz 282e83acae Merge pull request #18 from Michatec/renovate/kotlin-monorepo
Update plugin org.jetbrains.kotlin.android to v2.3.0
2025-12-19 12:18:27 +01:00
renovate[bot] 2fa6f9f368 Update dependency androidx.media3:media3-exoplayer-hls to v1.9.0 2025-12-19 11:18:25 +00:00
renovate[bot] 1abcc04c72 Update dependency androidx.media3:media3-datasource-okhttp to v1.9.0 2025-12-19 11:18:22 +00:00
renovate[bot] a478aef494 Update dependency com.google.code.gson:gson to v2.13.2 2025-12-19 11:18:19 +00:00
renovate[bot] 68f0829a2f Update dependency androidx.navigation:navigation-ui-ktx to v2.9.6 2025-12-19 11:18:17 +00:00
Michachatz 4dfcb13e6c Merge pull request #19 from Michatec/renovate/actions-cache-5.x
Update actions/cache action to v5
2025-12-19 12:18:12 +01:00
Michachatz e8fae6571c Merge pull request #20 from Michatec/renovate/actions-checkout-6.x
Update actions/checkout action to v6
2025-12-19 12:17:45 +01:00
Michachatz f1b1275e9d Merge pull request #21 from Michatec/renovate/actions-setup-java-5.x
Update actions/setup-java action to v5
2025-12-19 12:17:33 +01:00
Michachatz 3741b7ec97 Merge pull request #22 from Michatec/renovate/major-github-artifact-actions
Update GitHub Artifact Actions (major)
2025-12-19 12:17:15 +01:00
Michachatz bc1b3e5835 Merge pull request #15 from Michatec/renovate/gradle-8.x
Update Gradle to v8.14.3
2025-12-19 12:16:52 +01:00
renovate[bot] d850df3b4e Update GitHub Artifact Actions 2025-12-19 11:16:31 +00:00
renovate[bot] 17851e36b8 Update actions/setup-java action to v5 2025-12-19 11:16:27 +00:00
renovate[bot] a8e7ea6ea9 Update actions/checkout action to v6 2025-12-19 11:16:24 +00:00
Michachatz abdf9f7fb6 Merge pull request #8 from Michatec/renovate/androidx.activity-activity-ktx-1.x
Update dependency androidx.activity:activity-ktx to v1.12.2
2025-12-19 12:16:23 +01:00
renovate[bot] 8edfb975a8 Update actions/cache action to v5 2025-12-19 11:16:21 +00:00
renovate[bot] b3882dd97b Update plugin org.jetbrains.kotlin.android to v2.3.0 2025-12-19 11:16:15 +00:00
renovate[bot] 18c7c5e261 Update plugin com.android.library to v8.13.2 2025-12-19 11:16:12 +00:00
renovate[bot] 41db8e6446 Update plugin com.android.application to v8.13.2 2025-12-19 11:16:09 +00:00
renovate[bot] fdd0eb02c9 Update Gradle to v8.14.3 2025-12-19 11:16:05 +00:00
Michachatz bc10527af0 Merge pull request #10 from Michatec/renovate/androidx.media3-media3-exoplayer-1.x
Update dependency androidx.media3:media3-exoplayer to v1.9.0
2025-12-19 12:16:00 +01:00
Michachatz c44d51bc53 Merge pull request #12 from Michatec/renovate/androidx.media3-media3-session-1.x
Update dependency androidx.media3:media3-session to v1.9.0
2025-12-19 12:15:20 +01:00
Michachatz 4068c5363c Merge pull request #13 from Michatec/renovate/androidx.work-work-runtime-ktx-2.x
Update dependency androidx.work:work-runtime-ktx to v2.11.0
2025-12-19 12:15:03 +01:00
Michachatz 26619b6ead Merge pull request #14 from Michatec/renovate/com.google.android.material-material-1.x
Update dependency com.google.android.material:material to v1.13.0
2025-12-19 12:14:08 +01:00
renovate[bot] cc174c7d15 Update dependency com.google.android.material:material to v1.13.0 2025-12-19 11:13:28 +00:00
renovate[bot] a5281ca0ec Update dependency androidx.work:work-runtime-ktx to v2.11.0 2025-12-19 11:13:25 +00:00
renovate[bot] 0365952276 Update dependency androidx.media3:media3-session to v1.9.0 2025-12-19 11:13:21 +00:00
renovate[bot] e327cd036f Update dependency androidx.media3:media3-exoplayer to v1.9.0 2025-12-19 11:13:14 +00:00
renovate[bot] 45cb807ee2 Update dependency androidx.activity:activity-ktx to v1.12.2 2025-12-19 11:13:06 +00:00
Michachatz b18b1803b7 Merge pull request #3 from Michatec/renovate/androidx.navigation-navigation-fragment-ktx-2.x
Update dependency androidx.navigation:navigation-fragment-ktx to v2.9.6
2025-12-19 12:07:21 +01:00
Michachatz cda4970c5d Merge pull request #2 from Michatec/renovate/androidx.media-media-1.x
Update dependency androidx.media:media to v1.7.1
2025-12-19 12:05:54 +01:00
renovate[bot] 209f26cca8 Update dependency androidx.navigation:navigation-fragment-ktx to v2.9.6 2025-12-19 11:02:21 +00:00
renovate[bot] 1ff6c4e791 Update dependency androidx.media:media to v1.7.1 2025-12-19 11:02:18 +00:00
Michachatz 1bb6794ced Merge pull request #1 from Michatec/renovate/configure
Configure Renovate
2025-12-19 12:01:42 +01:00
renovate[bot] 147e308711 Add renovate.json 2025-12-12 07:50:21 +00:00
Michatec 26cb5cda08 Fix Version name
- and my mistake.
2025-06-11 18:00:12 +02:00
Michatec 6a74e64e87 Versionscode Bug Fixed 2025-06-11 17:52:16 +02:00
Michatec efa03f7529 New version coming 13 2025-06-11 17:43:36 +02:00
Michatec 0a56971fa2 Some Bugfixes and Improvments
- Update the libary gson.
- Deleted some unuseful Code.
- added some locals to locales config.
2025-06-11 17:36:47 +02:00
Michachatz 5ecbede8b5 Update gradle-publish.yml 2025-06-09 14:51:51 +02:00
117 changed files with 5118 additions and 1643 deletions
+38
View File
@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+18 -33
View File
@@ -1,14 +1,18 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json # yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Build and publish APK name: Build and publish APK
on: on:
workflow_dispatch:
push: push:
tags: branches: [ "main" ]
- '*' pull_request:
branches: [ "main" ]
env: env:
ANDROID_HOME: /usr/local/lib/android/sdk/ ANDROID_HOME: /usr/local/lib/android/sdk/
APK_PATH: app/build/outputs/apk/release/Radio-release-unsigned.apk APK_PATH: app/build/outputs/apk/release/Radio.apk
APKSIGNER: /usr/local/lib/android/sdk/build-tools/34.0.0/apksigner APKSIGNER: /usr/local/lib/android/sdk/build-tools/34.0.0/apksigner
ZIPALIGN: /usr/local/lib/android/sdk/build-tools/34.0.0/zipalign
jobs: jobs:
build: build:
@@ -17,10 +21,10 @@ jobs:
contents: write contents: write
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v6
- name: Setup JDK - name: Setup JDK
uses: actions/setup-java@v4 uses: actions/setup-java@v5
with: with:
java-version: 17 java-version: 17
distribution: adopt distribution: adopt
@@ -28,7 +32,7 @@ jobs:
- name: Cache Android SDK - name: Cache Android SDK
#id: cache-android-sdk #id: cache-android-sdk
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.ANDROID_HOME }} path: ${{ env.ANDROID_HOME }}
key: ${{ runner.os }}-android-sdk key: ${{ runner.os }}-android-sdk
@@ -37,9 +41,9 @@ jobs:
## It is not necessary to check for cache hit as it ## It is not necessary to check for cache hit as it
## will not download Android SDK again ## will not download Android SDK again
#if: steps.cache-android-sdk.outputs.cache-hit != 'true' #if: steps.cache-android-sdk.outputs.cache-hit != 'true'
uses: android-actions/setup-android@v3 uses: android-actions/setup-android@v4
with: with:
packages: '' packages: 'ndk;29.0.14206865'
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x ./gradlew run: chmod +x ./gradlew
@@ -50,6 +54,10 @@ jobs:
- name: Check APK path - name: Check APK path
run: ls -R app/build/outputs/apk run: ls -R app/build/outputs/apk
- name: Zipalign APK
run: |
${{ env.ZIPALIGN }} -v -p 4 ${{ env.APK_PATH }} app-release-aligned.apk
- name: Sign APK - name: Sign APK
env: env:
SIGN_CERT: ${{ secrets.SIGN_CERT }} SIGN_CERT: ${{ secrets.SIGN_CERT }}
@@ -57,35 +65,12 @@ jobs:
run: | run: |
echo "$SIGN_CERT" | base64 -d > cert.der echo "$SIGN_CERT" | base64 -d > cert.der
echo "$SIGN_KEY" | base64 -d > key.der echo "$SIGN_KEY" | base64 -d > key.der
mv ${{ env.APK_PATH }} app-release.apk ${{ env.APKSIGNER }} sign --key key.der --cert cert.der app-release-aligned.apk
${{ env.APKSIGNER }} sign --key key.der --cert cert.der app-release.apk
rm cert.der key.der rm cert.der key.der
- name: Zipalign APK
run: |
/usr/local/lib/android/sdk/build-tools/34.0.0/zipalign -v -p 4 app-release.apk app-release-aligned.apk
mv app-release-aligned.apk app-release.apk mv app-release-aligned.apk app-release.apk
- name: Upload artifact - name: Upload artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: app-release name: app-release
path: app-release.apk path: app-release.apk
publish:
runs-on: ubuntu-latest
needs: build
permissions:
contents: write
steps:
- name: Download artifact
uses: actions/download-artifact@v4
with:
name: app-release
path: app-release.apk
- name: Create release
uses: ncipollo/release-action@v1
with:
artifacts: "app-release.apk"
draft: true
+3
View File
@@ -5,3 +5,6 @@
/.idea /.idea
/build /build
/captures /captures
/gradle/gradle-daemon-jvm.properties
/.kotlin
/app/.cxx/
+16
View File
@@ -0,0 +1,16 @@
{
"configurations": [
{
"name": "Android",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
]
}
],
"version": 4
}
+3
View File
@@ -0,0 +1,3 @@
{
"C_Cpp.default.compilerPath": ""
}
+672 -17
View File
@@ -1,23 +1,678 @@
The MIT License (MIT) GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
===================== =====================
Copyright (c) 2025 - Michatec Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
-------------------------------- --------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy Preamble
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The GNU General Public License is a free, copyleft license for
all copies or substantial portions of the Software. software and other kinds of works.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR The licenses for most software and other practical works are designed
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, to take away your freedom to share and change the works. By contrast,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE the GNU General Public License is intended to guarantee your freedom to
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER share and change all versions of a program--to make sure it remains free
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, software for all its users. We, the Free Software Foundation, use the
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN GNU General Public License for most of our software; it applies also to
THE SOFTWARE. any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+45 -3
View File
@@ -1,19 +1,39 @@
<p align="center">
<a href="https://github.com/michatec/Radio/releases"><img src="https://img.shields.io/github/v/release/michatec/Radio?style=flat-square&include_prereleases&label=version" /></a>
<a href="https://github.com/michatec/Radio/releases"><img src="https://img.shields.io/github/downloads/michatec/Radio/total.svg?style=flat-square" /></a>
<a href="https://github.com/michatec/Radio/issues"><img src="https://img.shields.io/github/issues-raw/michatec/Radio.svg?style=flat-square&label=issues" /></a>
<a href="https://github.com/michatec/Radio/graphs/contributors"><img src="https://img.shields.io/github/contributors/michatec/Radio?style=flat-square" /></a>
</p>
<div align="center"> <div align="center">
### ️ About Radio ### ️ About Radio
**Radio is an application with a minimalist approach to listening to radio over the Internet.** <br> **Radio is an application with a minimalist approach to listening to radio over the Internet.** <br>
**Radio only offers a very basic search option, and it imports audio streaming links when you tap them in a web browser.** <br> **Radio only offers a very basic search option, and it imports audio streaming links when you tap them in a web browser.** <br>
**Radio now also supports Android TV (Beta) and Cast to Devices (Beta).** <br>
**Pull request are welcome at any time.**<br> **Pull request are welcome at any time.**<br>
**Radio is free software. It is released under the [MIT open source license](https://opensource.org/licenses/MIT).** **Radio is free software. It is released under the [GPLv3 open source license](https://opensource.org/licenses/GPL-3.0).**
</div> </div>
---------------------------------------- ----------------------------------------
<details>
<summary>❗Warning</summary>
<br>
<p>
Google has announced that, starting in 2026/2027, all apps on certified Android devices will require the developer to submit personal identity details directly to Google.
Since the developers of this app do not agree to this requirement, this app will no longer work on certified Android devices after that time.
</p>
<a href="https://github.com/woheller69/FreeDroidWarn">️ More Information</a>
</details>
----------------------------------------
<details> <details>
<summary>⚙️ Install Radio</summary> <summary>⚙️ Install Radio</summary>
<br> <br>
<a href="https://github.com/michatec/Radio/releases/latest"><img src="https://user-images.githubusercontent.com/15986930/229208526-e5a63be5-0d0b-48ab-a222-9f2f2faf0ee4.png" height="80px"></a> <a href="https://github.com/michatec/Radio/releases/latest"><img src="https://user-images.githubusercontent.com/15986930/229208526-e5a63be5-0d0b-48ab-a222-9f2f2faf0ee4.png" alt="Preview" height="80px"></a>
</details> </details>
---------------------------------------- ----------------------------------------
@@ -57,10 +77,32 @@ You can help out the radio-browser.info community by [adding the missing station
---------------------------------------- ----------------------------------------
<details>
<summary>📺 Android TV Controls</summary>
<br>
When **Edit Stations** is enabled:
- Press **← (Left)** on the remote to open the detailed station editing area
- Press **3** or **Back** to close the editing area
**General TV** Controls:
- Press **0** or **DEL** to remove the selected radio station
- Press **1** or **SPACE** to make the selected radio station favourite
- Press **2** or **PLUS** to reorder the selected radio station
</details>
----------------------------------------
<details> <details>
<summary>📜️ Credit</summary> <summary>📜️ Credit</summary>
Base app Michatec & [TRANSISTOR](https://codeberg.org/y20k/transistor). - [Radio Browser](http://www.radio-browser.info/) for providing the radio station database
- [AndroidX Leanback](https://developer.android.com/jetpack/androidx/releases/leanback) for providing the Android TV UI components
- Michatec for developing the app and maintaining the project
- All the contributors who have contributed to the project by submitting pull requests, reporting issues, or providing feedback
</details> </details>
<div align="right"> <div align="right">
+49 -22
View File
@@ -1,19 +1,32 @@
apply plugin: 'com.android.application' plugins {
apply plugin: 'kotlin-android' alias libs.plugins.android.application
apply plugin: 'kotlin-parcelize' id 'kotlin-parcelize'
}
androidComponents {
onVariants(selector().all()) { variant ->
variant.outputs.forEach { output ->
output.outputFileName.set("Radio.apk")
}
}
}
android { android {
namespace 'com.michatec.radio' namespace 'com.michatec.radio'
compileSdk 35 compileSdk 36
defaultConfig { defaultConfig {
applicationId 'com.michatec.radio' applicationId 'com.michatec.radio'
minSdk 28 minSdk 28
targetSdk 35 targetSdk 36
versionCode 129 versionCode 145
versionName '12.9' versionName '14.5'
resourceConfigurations += ['en', 'de', 'el', 'nl', 'pl', 'ru','uk', 'ja', 'da', 'fr'] resourceConfigurations += ['en', 'de', 'el', 'nl', 'pl', 'ru','uk', 'ja', 'da', 'fr']
setProperty('archivesBaseName', 'Radio') externalNativeBuild {
cmake {
cppFlags ''
}
}
} }
compileOptions { compileOptions {
@@ -41,28 +54,42 @@ android {
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
} }
} }
ndkVersion "29.0.14206865"
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.22.1'
}
}
} }
dependencies { dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.jar'])
// Google Stuff // // Google Stuff //
implementation 'com.google.android.material:material:1.12.0' implementation libs.material
implementation 'com.google.code.gson:gson:2.10.1' implementation libs.gson
implementation libs.play.services.cast.framework
// AndroidX Stuff // // AndroidX Stuff //
implementation 'androidx.activity:activity-ktx:1.10.1' implementation libs.core.ktx
implementation 'androidx.palette:palette-ktx:1.0.0' implementation libs.activity.ktx
implementation 'androidx.preference:preference-ktx:1.2.1' implementation libs.palette.ktx
implementation 'androidx.media:media:1.7.0' implementation libs.preference.ktx
implementation 'androidx.media3:media3-exoplayer:1.7.1' implementation libs.media
implementation 'androidx.media3:media3-exoplayer-hls:1.7.1' implementation libs.media3.exoplayer
implementation 'androidx.media3:media3-session:1.7.1' implementation libs.media3.exoplayer.hls
implementation 'androidx.media3:media3-datasource-okhttp:1.7.1' implementation libs.media3.session
implementation 'androidx.navigation:navigation-fragment-ktx:2.9.0' implementation libs.media3.cast
implementation 'androidx.navigation:navigation-ui-ktx:2.9.0' implementation libs.media3.datasource.okhttp
implementation 'androidx.work:work-runtime-ktx:2.10.1' implementation libs.navigation.fragment.ktx
implementation libs.navigation.ui.ktx
implementation libs.work.runtime.ktx
implementation libs.leanback
implementation libs.freedroidwarn
// Volley HTTP request // // Volley HTTP request //
implementation 'com.android.volley:volley:1.2.1' implementation libs.volley
implementation libs.material3
} }
+27 -28
View File
@@ -1,6 +1,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<uses-feature
android:name="android.software.leanback"
android:required="false" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
@@ -10,6 +17,7 @@
<application <application
android:name=".Radio" android:name=".Radio"
android:allowBackup="true" android:allowBackup="true"
android:banner="@mipmap/ic_launcher"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules" android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
@@ -21,10 +29,9 @@
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme" android:theme="@style/AppTheme"
android:usesCleartextTraffic="true" android:usesCleartextTraffic="true"
tools:targetApi="tiramisu"> tools:targetApi="33">
<!-- ANDROID AUTO SUPPORT --> <!-- ANDROID AUTO SUPPORT -->
<!-- https://developer.android.com/training/auto/audio/ -->
<meta-data <meta-data
android:name="com.google.android.gms.car.application" android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" /> android:resource="@xml/automotive_app_desc" />
@@ -32,56 +39,60 @@
android:name="com.google.android.gms.car.notification.SmallIcon" android:name="com.google.android.gms.car.notification.SmallIcon"
android:resource="@mipmap/ic_launcher" /> android:resource="@mipmap/ic_launcher" />
<!-- Main activity for radio station playback on phone --> <!-- GOOGLE CAST SUPPORT -->
<receiver android:name="androidx.mediarouter.media.MediaTransferReceiver" />
<meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="com.michatec.radio.CastOptionsProvider" />
<activity
android:name=".ExpandedControllerActivity"
android:exported="false"
android:launchMode="singleTask" />
<!-- Main activity for radio station playback on phone and TV -->
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:configChanges="orientation|screenSize" android:configChanges="orientation|screenSize"
android:windowSoftInputMode="adjustPan" android:windowSoftInputMode="adjustPan"
android:theme="@style/SplashTheme"
android:exported="true"> android:exported="true">
<!-- react to main intents -->
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter> </intent-filter>
<!-- react to be recognized as a music player -->
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MUSIC_PLAYER" /> <action android:name="android.intent.action.MUSIC_PLAYER" />
<category android:name="android.intent.category.CATEGORY_APP_MUSIC" /> <category android:name="android.intent.category.CATEGORY_APP_MUSIC" />
</intent-filter> </intent-filter>
<!-- react to voice searches, like "Play Security Now" -->
<intent-filter> <intent-filter>
<action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" /> <action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
</intent-filter> </intent-filter>
<!-- react to playlist-links based on file extension --> <intent-filter android:autoVerify="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" /> <data android:scheme="http" />
<data android:scheme="https" /> <data android:scheme="https" />
<data android:host="*" /> <data android:host="*" tools:ignore="AppLinkUrlError" />
<data android:pathPattern=".*\\.m3u" /> <data android:pathPattern=".*\\.m3u" />
<data android:pathPattern=".*\\.m3u8" /> <data android:pathPattern=".*\\.m3u8" />
<data android:pathPattern=".*\\.pls" /> <data android:pathPattern=".*\\.pls" />
</intent-filter> </intent-filter>
<!-- react to playlist-links based on mimetype --> <intent-filter android:autoVerify="false">
<intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" /> <data android:scheme="http" />
<data android:scheme="https" /> <data android:scheme="https" />
<data android:host="*" /> <data android:host="*" tools:ignore="AppLinkUrlError" />
<data android:mimeType="audio/x-scpls" /> <data android:mimeType="audio/x-scpls" />
<data android:mimeType="audio/mpegurl" /> <data android:mimeType="audio/mpegurl" />
<data android:mimeType="audio/x-mpegurl" /> <data android:mimeType="audio/x-mpegurl" />
@@ -92,11 +103,9 @@
<data android:mimeType="application/octet-stream" /> <data android:mimeType="application/octet-stream" />
</intent-filter> </intent-filter>
<!-- react to hls playlist-links based on mimetype -->
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" /> <data android:scheme="content" />
<data android:host="*" /> <data android:host="*" />
<data android:mimeType="audio/x-scpls" /> <data android:mimeType="audio/x-scpls" />
@@ -108,20 +117,16 @@
<data android:mimeType="application/vnd.apple.mpegurl.audio" /> <data android:mimeType="application/vnd.apple.mpegurl.audio" />
</intent-filter> </intent-filter>
<!-- react to "start player service" intents -->
<intent-filter> <intent-filter>
<action android:name="com.michatec.radio.action.START_PLAYER_SERVICE" /> <action android:name="com.michatec.radio.action.START_PLAYER_SERVICE" />
</intent-filter> </intent-filter>
<!-- App Shortcuts -->
<meta-data <meta-data
android:name="android.app.shortcuts" android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" /> android:resource="@xml/shortcuts" />
</activity> </activity>
<!-- Player Service -->
<service <service
android:name=".PlayerService" android:name=".PlayerService"
android:enabled="true" android:enabled="true"
@@ -135,8 +140,6 @@
</intent-filter> </intent-filter>
</service> </service>
<!-- handles completed downloads -->
<receiver <receiver
android:name=".helpers.DownloadFinishedReceiver" android:name=".helpers.DownloadFinishedReceiver"
android:exported="true"> android:exported="true">
@@ -145,8 +148,6 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- handles media buttons -->
<receiver <receiver
android:name="androidx.media.session.MediaButtonReceiver" android:name="androidx.media.session.MediaButtonReceiver"
android:exported="true"> android:exported="true">
@@ -155,8 +156,6 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- file provider -->
<provider <provider
android:name="androidx.core.content.FileProvider" android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider" android:authorities="${applicationId}.provider"
+42
View File
@@ -0,0 +1,42 @@
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html.
# For more examples on how to use CMake, see https://github.com/android/ndk-samples.
# Sets the minimum CMake version required for this project.
cmake_minimum_required(VERSION 3.22.1)
# Declares the project name. The project name can be accessed via ${ PROJECT_NAME},
# Since this is the top level CMakeLists.txt, the project name is also accessible
# with ${CMAKE_PROJECT_NAME} (both CMake variables are in-sync within the top level
# build script scope).
project("radio")
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
#
# In this top level CMakeLists.txt, ${CMAKE_PROJECT_NAME} is used to define
# the target library name; in the sub-module's CMakeLists.txt, the project name
# is preferred for the same purpose.
#
# In order to load a library into your app from Java/Kotlin, you must call
# System.loadLibrary() and pass the name of the library defined here;
# for GameActivity/NativeActivity derived applications, the same library name must be
# used in the AndroidManifest.xml file.
add_library(dsp SHARED
dsp.cpp)
add_library(extra SHARED
extra.cpp)
# Specifies libraries CMake should link to your target library. You
# can link libraries from various origins, such as libraries defined in this
# build script, prebuilt third-party libraries, or Android system libraries.
target_link_libraries(dsp
android
log)
target_link_libraries(extra
android
log)
+458
View File
@@ -0,0 +1,458 @@
#include <jni.h>
#include <vector>
#include <cmath>
#include <complex>
#include <array>
#include <atomic>
#if defined(__ARM_NEON)
#include <arm_neon.h>
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static std::atomic<float> gSampleRate(44100.0f);
static constexpr int FFT_SIZE = 2048;
static constexpr int NUM_EQ_BANDS = 10;
static constexpr float INV_32768 = 1.0f / 32768.0f;
static constexpr float SQRT_2_INV = 0.70710678f;
static constexpr float DENORMAL_OFFSET = 1e-18f;
static constexpr float INTERPOLATION_SPEED = 0.5f;
static constexpr std::array<float, NUM_EQ_BANDS> EQ_FREQUENCIES = {
31.25f, 62.5f, 125.0f, 250.0f, 500.0f,
1000.0f, 2000.0f, 4000.0f, 8000.0f, 16000.0f
};
struct alignas(16) EqBandInterpolator {
std::atomic<float> targetGain{0.0f};
std::atomic<float> currentGain{0.0f};
float a0 = 1.0f, a1 = 0.0f, a2 = 0.0f, b1 = 0.0f, b2 = 0.0f;
float z1 = 0.0f, z2 = 0.0f;
bool active = false;
inline void setTargetGain(float g) { targetGain.store(g, std::memory_order_release); }
inline void updateInterpolation() {
float target = targetGain.load(std::memory_order_acquire);
float current = currentGain.load(std::memory_order_relaxed);
float diff = target - current;
if (std::abs(diff) > 0.001f) {
currentGain.store(current + diff * INTERPOLATION_SPEED, std::memory_order_release);
}
}
inline float process(float x) {
if (!active) return x;
updateInterpolation();
float y = x * a0 + z1;
z1 = x * a1 + z2 - b1 * y + DENORMAL_OFFSET;
z2 = x * a2 - b2 * y;
return y;
}
inline void setCoefficients(float sr, float f, float g, float bw) {
active = true;
const float A = powf(10.0f, g / 60.0f);
const float w = 2.0f * static_cast<float>(M_PI) * f / sr;
const float alpha = sinf(w) * sinhf(logf(2.0f) / 2.0f * bw * w / sinf(w));
const float c = cosf(w);
const float a0_raw = 1.0f + alpha / A;
const float invA0 = 1.0f / a0_raw;
a0 = (1.0f + alpha * A) * invA0;
a1 = (-2.0f * c) * invA0;
a2 = (1.0f - alpha * A) * invA0;
b1 = (-2.0f * c) * invA0;
b2 = (1.0f - alpha / A) * invA0;
}
};
struct alignas(16) BassFilter {
alignas(16) float a0 = 1.2f, a1 = 1.2f, a2 = 1.2f, b1 = 0.0f, b2 = 0.0f;
alignas(16) float z1 = 0.0f, z2 = 0.0f;
std::atomic<bool> active{false};
std::atomic<float> targetGain{0.0f};
std::atomic<float> currentGain{0.0f};
inline void updateInterpolation() {
float target = targetGain.load(std::memory_order_acquire);
float current = currentGain.load(std::memory_order_relaxed);
float diff = target - current;
if (std::abs(diff) > 0.001f) {
currentGain.store(current + diff * INTERPOLATION_SPEED, std::memory_order_release);
}
}
inline float process(float x) {
if (!active.load(std::memory_order_acquire)) return x;
updateInterpolation();
float y = x * a0 + z1;
z1 = x * a1 + z2 - b1 * y + DENORMAL_OFFSET;
z2 = x * a2 - b2 * y;
if(y > 1.2f) y = 1.2f; else if(y < -1.2f) y = -1.2f;
return y;
}
void setCoefficients(float sr, float f, float g, float q){
float A=powf(10.0f,g/60.0f);
float w=2.0f*static_cast<float>(M_PI)*f/sr;
float alpha=sinf(w)/2.0f*sqrtf((A+1.0f/A)*(1.0f/q-1.0f)+2.0f);
float c=cosf(w),sqrtA=sqrtf(A);
float a0_raw=(A+1.0f)+(A-1.0f)*c+2.0f*sqrtA*alpha;
float invA0=1.0f/a0_raw;
a0=A*((A+1.0f)-(A-1.0f)*c+2.0f*sqrtA*alpha)*invA0;
a1=2.0f*A*((A-1.0f)-(A+1.0f)*c)*invA0;
a2=A*((A+1.0f)-(A-1.0f)*c-2.0f*sqrtA*alpha)*invA0;
b1=-2.0f*((A-1.0f)+(A+1.0f)*c)*invA0;
b2=((A+1.0f)+(A-1.0f)*c-2.0f*sqrtA*alpha)*invA0;
}
void applyGain(float sr) {
float g = currentGain.load(std::memory_order_acquire);
setCoefficients(sr, 150.0f, g, SQRT_2_INV);
}
};
class ReverbOptimized {
struct DelayLine {
float buffer[48000]{};
int size = 48000;
int pos = 0;
inline float read(float delaySamples) {
float readPos = static_cast<float>(pos) - delaySamples;
if (readPos < 0.0f) readPos += static_cast<float>(size);
int i1 = static_cast<int>(readPos);
int i2 = (i1 + 1) % size;
float frac = readPos - static_cast<float>(i1);
return buffer[i1] * (1.0f - frac) + buffer[i2] * frac;
}
inline void write(float x) {
buffer[pos] = x;
pos++;
if (pos >= size) pos = 0;
}
};
DelayLine delays[8];
float feedback[8] = {
0.78f, 0.80f, 0.82f, 0.84f,
0.76f, 0.79f, 0.81f, 0.83f
};
float baseDelay[8] = {
1423.0f, 1557.0f, 1617.0f, 1789.0f,
1867.0f, 1999.0f, 2137.0f, 2251.0f
};
float modPhase[8] = {};
float modSpeed[8] = {
0.10f, 0.12f, 0.09f, 0.11f,
0.13f, 0.08f, 0.14f, 0.07f
};
public:
std::atomic<float> mix{0.0f};
inline float processSample(float x) {
float m = mix.load(std::memory_order_relaxed);
if (m < 0.01f) return x;
float out = 0.0f;
#pragma GCC unroll 8
for (int i = 0; i < 8; i++) {
modPhase[i] += modSpeed[i];
if (modPhase[i] > 2.0f * static_cast<float>(M_PI)) modPhase[i] -= 2.0f * static_cast<float>(M_PI);
float mod = sinf(modPhase[i]) * 5.0f;
float delayTime = baseDelay[i] + mod;
float delayed = delays[i].read(delayTime);
float input = x + delayed * feedback[i] + DENORMAL_OFFSET;
delays[i].write(input);
out += delayed;
}
return x * (1.0f - m) + (out * 0.125f) * m;
}
inline void processBlock(float* __restrict__ left, float* __restrict__ right, int count) {
float m = mix.load(std::memory_order_relaxed);
if (m < 0.01f) return;
for (int i = 0; i < count; i++) {
float l = processSample(left[i]);
float r = processSample(right[i]);
float wetL = l * 0.7f + r * 0.3f;
float wetR = r * 0.7f + l * 0.3f;
left[i] = wetL;
right[i] = wetR;
}
}
};
class CompressorOptimized {
public:
std::atomic<float> threshold{0.3f}, ratio{4.0f}, attack{0.08f}, release{0.8f};
std::atomic<float> sampleRate{44100.0f};
std::atomic<bool> enabled{false};
private:
float envelopeL = 0.0f, envelopeR = 0.0f;
float attackCoef = 0.0f, releaseCoef = 0.0f;
public:
inline void updateCoefficients() {
float a = attack.load(std::memory_order_relaxed);
float r = release.load(std::memory_order_relaxed);
float sr = sampleRate.load(std::memory_order_relaxed);
attackCoef = expf(-1.0f / (a * sr));
releaseCoef = expf(-1.0f / (r * sr));
}
inline void processBlock(float* __restrict__ buffer, int count, float& envelope) {
updateCoefficients();
float th = threshold.load(std::memory_order_acquire);
float rt = ratio.load(std::memory_order_acquire);
for(int i=0; i<count; i++){
float absInput = fabsf(buffer[i]);
envelope = (absInput > envelope) ? attackCoef*envelope + (1.0f-attackCoef)*absInput : releaseCoef*envelope + (1.0f-releaseCoef)*absInput;
float gain = (envelope>th)? (th + (envelope-th)/rt)/(envelope+1e-9f) : 1.0f;
buffer[i]*=gain;
}
}
inline void process(float* __restrict__ left, float* __restrict__ right, int count) {
if (!enabled.load(std::memory_order_acquire)) return;
processBlock(left, count, envelopeL);
processBlock(right, count, envelopeR);
}
};
static std::atomic<float> gStereoWidth{1.0f};
alignas(16) std::array<float, 4096> gLeftBuf, gRightBuf;
alignas(16) std::array<float, 256> gFFTData;
inline void fastFFT(std::complex<float>* __restrict__ data, int n) {
for (int i = 1, j = 0; i < n; i++) {
int bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) std::swap(data[i], data[j]);
}
for (int len = 2; len <= n; len <<= 1) {
float ang = -2.0f * static_cast<float>(M_PI) / static_cast<float>(len);
std::complex<float> wlen(cosf(ang), sinf(ang));
for (int i = 0; i < n; i += len) {
std::complex<float> w(1.0f);
for (int j = 0; j < len / 2; j++) {
std::complex<float> u = data[i + j];
std::complex<float> v = data[i + j + len / 2] * w;
data[i + j] = u + v;
data[i + j + len / 2] = u - v;
w *= wlen;
}
}
}
}
inline void applyHannWindowToReal(std::complex<float>* __restrict__ data, int size) {
const auto fSizeMinus1 = static_cast<float>(size - 1);
for (int i = 0; i < size; i++) {
float window = 0.5f * (1.0f - cosf(2.0f * static_cast<float>(M_PI) * static_cast<float>(i) / fSizeMinus1));
data[i] = std::complex<float>(data[i].real() * window, data[i].imag());
}
}
inline float fastSoftClip(float x) {
float ax = fabsf(x);
float sign = x > 0.0f ? 1.0f : -1.0f;
if (ax > 1.0f) return sign;
return x * (1.5f - 0.5f * x * x);
}
static EqBandInterpolator gEqL[NUM_EQ_BANDS];
static EqBandInterpolator gEqR[NUM_EQ_BANDS];
static BassFilter gBassL, gBassR;
static CompressorOptimized gCompressor;
static ReverbOptimized gReverbL, gReverbR;
static std::array<std::complex<float>, FFT_SIZE> gFFTWork;
static int gEqUpdateCounter = 0;
inline void updateAllEqBands() {
float sr = gSampleRate.load(std::memory_order_acquire);
for (int b = 0; b < NUM_EQ_BANDS; b++) {
float g = gEqL[b].targetGain.load(std::memory_order_acquire);
gEqL[b].setCoefficients(sr, EQ_FREQUENCIES[static_cast<size_t>(b)], g, 1.0f);
gEqR[b].setCoefficients(sr, EQ_FREQUENCIES[static_cast<size_t>(b)], g, 1.0f);
}
}
extern "C" {
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_setSampleRate(JNIEnv*, jobject, jfloat sr) {
gSampleRate.store(sr, std::memory_order_release);
gCompressor.sampleRate.store(sr, std::memory_order_release);
gBassL.applyGain(sr);
gBassR.applyGain(sr);
gEqUpdateCounter = 1;
}
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_setDrcEnabled(JNIEnv*, jobject, jboolean e) {
gCompressor.enabled.store(e == JNI_TRUE, std::memory_order_release);
}
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_setReverbMix(JNIEnv*, jobject, jfloat m) {
gReverbL.mix.store(m, std::memory_order_release);
gReverbR.mix.store(m, std::memory_order_release);
}
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_setEqFull(JNIEnv* env, jobject thiz, jfloatArray gains) {
if (!gains) return;
jsize len = env->GetArrayLength(gains);
int bandsToUpdate = std::min(static_cast<int>(len), NUM_EQ_BANDS);
jfloat* gainsPtr = env->GetFloatArrayElements(gains, nullptr);
if (!gainsPtr) return;
for (int b = 0; b < bandsToUpdate; b++) {
gEqL[b].setTargetGain(gainsPtr[b]);
gEqR[b].setTargetGain(gainsPtr[b]);
}
gEqUpdateCounter = 1;
env->ReleaseFloatArrayElements(gains, gainsPtr, JNI_ABORT);
}
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_setBassBoost(JNIEnv*, jobject, jfloat g) {
float scaledGain = g * 4.0f;
gBassL.targetGain.store(scaledGain, std::memory_order_release);
gBassR.targetGain.store(scaledGain, std::memory_order_release);
float sr = gSampleRate.load(std::memory_order_acquire);
gBassL.applyGain(sr);
gBassR.applyGain(sr);
if (std::abs(g) > 0.01f) {
gBassL.active.store(true, std::memory_order_release);
gBassR.active.store(true, std::memory_order_release);
} else {
gBassL.active.store(false, std::memory_order_release);
gBassR.active.store(false, std::memory_order_release);
}
}
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_setStereoWidth(JNIEnv*, jobject, jfloat w) {
gStereoWidth.store(fmaxf(0.0f, fminf(w, 2.0f)), std::memory_order_release);
}
JNIEXPORT jfloatArray JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_getFftData(JNIEnv* env, jobject) {
jfloatArray arr = env->NewFloatArray(256);
env->SetFloatArrayRegion(arr, 0, 256, gFFTData.data());
return arr;
}
inline void computeLogarithmicFFT(float* output, const std::complex<float>* input, int inputSize) {
float sr = gSampleRate.load(std::memory_order_acquire);
float binWidth = sr / (2.0f * static_cast<float>(inputSize));
constexpr int NUM_BANDS = 256;
constexpr float MIN_FREQ = 20.0f;
constexpr float MAX_FREQ = 20000.0f;
float logMin = logf(MIN_FREQ);
float logMax = logf(MAX_FREQ);
float logRange = logMax - logMin;
for (int b = 0; b < NUM_BANDS; b++) {
float f1 = expf(logMin + (logRange * static_cast<float>(b) / static_cast<float>(NUM_BANDS)));
float f2 = expf(logMin + (logRange * static_cast<float>(b + 1) / static_cast<float>(NUM_BANDS)));
int idx1 = static_cast<int>(f1 / binWidth);
int idx2 = static_cast<int>(f2 / binWidth);
idx1 = std::max(0, std::min(idx1, inputSize - 1));
idx2 = std::max(0, std::min(idx2, inputSize - 1));
float sum = 0.0f;
int count = idx2 - idx1 + 1;
for (int i = idx1; i <= idx2 && i < inputSize; i++) {
sum += std::abs(input[i]);
}
float avg = (count > 0) ? sum / static_cast<float>(count) : 0.0f;
output[b] = avg * 0.5f;
}
}
JNIEXPORT void JNICALL Java_com_michatec_radio_helpers_NativeAudioProcessor_processAudioDirect(JNIEnv* env, jobject, jobject byteBuffer, jint size) {
auto* buffer = static_cast<jshort*>(env->GetDirectBufferAddress(byteBuffer));
if (!buffer) return;
int numFrames = (size / 2) / 2;
if (numFrames > 4096) numFrames = 4096;
if (gEqUpdateCounter > 0) {
updateAllEqBands();
gEqUpdateCounter--;
}
for (int i = 0; i < numFrames; i++) {
gLeftBuf[static_cast<size_t>(i)] = static_cast<float>(buffer[i * 2]) * INV_32768;
gRightBuf[static_cast<size_t>(i)] = static_cast<float>(buffer[i * 2 + 1]) * INV_32768;
}
for (int i = 0; i < numFrames; i++) {
float xL = gLeftBuf[static_cast<size_t>(i)];
float xR = gRightBuf[static_cast<size_t>(i)];
for (int b = 0; b < NUM_EQ_BANDS; b++) {
xL = gEqL[b].process(xL);
xR = gEqR[b].process(xR);
}
gLeftBuf[static_cast<size_t>(i)] = xL;
gRightBuf[static_cast<size_t>(i)] = xR;
}
for(int i = 0; i < numFrames; i++) {
gLeftBuf[static_cast<size_t>(i)] = gBassL.process(gLeftBuf[static_cast<size_t>(i)]);
gRightBuf[static_cast<size_t>(i)] = gBassR.process(gRightBuf[static_cast<size_t>(i)]);
}
gReverbL.processBlock(gLeftBuf.data(), gRightBuf.data(), numFrames);
float stereoWidth = gStereoWidth.load(std::memory_order_relaxed);
if (stereoWidth != 1.0f) {
float halfWidth = stereoWidth * 0.5f;
for (int j = 0; j < numFrames; j++) {
float mid = (gLeftBuf[static_cast<size_t>(j)] + gRightBuf[static_cast<size_t>(j)]) * 0.5f;
float side = (gLeftBuf[static_cast<size_t>(j)] - gRightBuf[static_cast<size_t>(j)]) * halfWidth;
gLeftBuf[static_cast<size_t>(j)] = mid + side;
gRightBuf[static_cast<size_t>(j)] = mid - side;
}
}
gCompressor.process(gLeftBuf.data(), gRightBuf.data(), numFrames);
if (numFrames >= FFT_SIZE) {
for (int k = 0; k < FFT_SIZE; k++) {
gFFTWork[static_cast<size_t>(k)] = std::complex<float>(gLeftBuf[static_cast<size_t>(k)], 0.0f);
}
} else {
for (int k = 0; k < numFrames; k++) {
gFFTWork[static_cast<size_t>(k)] = std::complex<float>(gLeftBuf[static_cast<size_t>(k)], 0.0f);
}
for (int k = numFrames; k < FFT_SIZE; k++) {
gFFTWork[static_cast<size_t>(k)] = std::complex<float>(0.0f, 0.0f);
}
}
applyHannWindowToReal(gFFTWork.data(), FFT_SIZE);
fastFFT(gFFTWork.data(), FFT_SIZE);
computeLogarithmicFFT(gFFTData.data(), gFFTWork.data(), FFT_SIZE / 2);
for (int k = 0; k < numFrames; k++) {
buffer[k * 2] = static_cast<jshort>(fastSoftClip(gLeftBuf[static_cast<size_t>(k)]) * 32767.0f);
buffer[k * 2 + 1] = static_cast<jshort>(fastSoftClip(gRightBuf[static_cast<size_t>(k)]) * 32767.0f);
}
}
}
+86
View File
@@ -0,0 +1,86 @@
#include <jni.h>
#include <android/native_window_jni.h>
#include <android/native_window.h>
#include <android/log.h>
#include <vector>
#include <algorithm>
#include <cmath>
extern "C" {
JNIEXPORT void JNICALL
Java_com_michatec_radio_helpers_ExtrasHelper_visualize(JNIEnv *env, jclass clazz, jobject surface, jfloatArray data) {
if (!surface) return;
ANativeWindow* window = ANativeWindow_fromSurface(env, surface);
if (!window) return;
jsize len = env->GetArrayLength(data);
if (len == 0) {
ANativeWindow_release(window);
return;
}
jfloat* body = env->GetFloatArrayElements(data, nullptr);
ANativeWindow_Buffer buffer;
ANativeWindow_setBuffersGeometry(window, 0, 0, WINDOW_FORMAT_RGBA_8888);
if (ANativeWindow_lock(window, &buffer, nullptr) == 0) {
auto* pixels = static_cast<uint32_t*>(buffer.bits);
// Clear background (Dark Grey)
for (int y = 0; y < buffer.height; y++) {
uint32_t* row = pixels + (y * buffer.stride);
for (int x = 0; x < buffer.width; x++) {
row[x] = 0xFF121212;
}
}
// Draw bars - fewer bins = thicker bars
int displayBins = 40;
float barWidth = static_cast<float>(buffer.width) / static_cast<float>(displayBins);
int padding = static_cast<int>(barWidth * 0.2f);
if (padding < 1) padding = 1;
for (int i = 0; i < displayBins; i++) {
// Map display bin to data index
int dataIdx = (i * len) / displayBins;
float val = body[dataIdx];
// Use square root to compress the range (so peaks don't hit the top too easily)
// and a lower multiplier (0.4f) to reduce overall height
float scaledVal = sqrtf(val) * 0.5f;
int barHeight = static_cast<int>(scaledVal * static_cast<float>(buffer.height));
// Cap height at 75% to leave some room at the top
int maxH = static_cast<int>(static_cast<float>(buffer.height) * 0.75f);
if (barHeight > maxH) barHeight = maxH;
if (barHeight < 4) barHeight = 4; // Minimal visible line
int startX = static_cast<int>(static_cast<float>(i) * barWidth);
int endX = static_cast<int>(static_cast<float>(i + 1) * barWidth);
int drawStartX = startX + padding;
int drawEndX = endX - padding;
if (drawEndX <= drawStartX) drawEndX = drawStartX + 1;
int barBottom = buffer.height - 4; // Bottom margin
int barTop = barBottom - barHeight;
for (int x = drawStartX; x < drawEndX; x++) {
if (x < 0 || x >= buffer.width) continue;
for (int y = barTop; y < barBottom; y++) {
if (y < 0 || y >= buffer.height) continue;
// Using the same color, but now height is controlled
pixels[y * buffer.stride + x] = 0xFFC5DA03;
}
}
}
ANativeWindow_unlockAndPost(window);
}
env->ReleaseFloatArrayElements(data, body, JNI_ABORT);
ANativeWindow_release(window);
}
} // extern "C"
@@ -0,0 +1,214 @@
package com.michatec.radio
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import androidx.appcompat.widget.SearchView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textview.MaterialTextView
import com.michatec.radio.collection.CollectionViewModel
import com.michatec.radio.core.Station
import com.michatec.radio.helpers.CollectionHelper
import com.michatec.radio.helpers.NetworkHelper
import com.michatec.radio.search.DirectInputCheck
import com.michatec.radio.search.RadioBrowserResult
import com.michatec.radio.search.RadioBrowserSearch
import com.michatec.radio.search.SearchResultAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class AddStationFragment : Fragment(),
SearchResultAdapter.SearchResultAdapterListener,
RadioBrowserSearch.RadioBrowserSearchListener,
DirectInputCheck.DirectInputCheckListener {
private lateinit var collectionViewModel: CollectionViewModel
private lateinit var stationSearchBoxView: SearchView
private lateinit var searchRequestProgressIndicator: ProgressBar
private lateinit var noSearchResultsTextView: MaterialTextView
private lateinit var stationSearchResultList: RecyclerView
private lateinit var positiveButton: Button
private lateinit var negativeButton: Button
private lateinit var searchResultAdapter: SearchResultAdapter
private lateinit var radioBrowserSearch: RadioBrowserSearch
private lateinit var directInputCheck: DirectInputCheck
private var station: Station = Station()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// We reuse the dialog layout as it's already optimized for TV in layout-television
val view = inflater.inflate(R.layout.dialog_find_station, container, false)
collectionViewModel = ViewModelProvider(requireActivity())[CollectionViewModel::class.java]
radioBrowserSearch = RadioBrowserSearch(this)
directInputCheck = DirectInputCheck(this)
stationSearchBoxView = view.findViewById(R.id.station_search_box_view)
searchRequestProgressIndicator = view.findViewById(R.id.search_request_progress_indicator)
stationSearchResultList = view.findViewById(R.id.station_search_result_list)
noSearchResultsTextView = view.findViewById(R.id.no_results_text_view)
positiveButton = view.findViewById(R.id.dialog_positive_button)
negativeButton = view.findViewById(R.id.dialog_negative_button)
setupRecyclerView()
setupSearchView()
positiveButton.setOnClickListener {
addStationAndExit()
}
negativeButton.setOnClickListener {
searchResultAdapter.stopPrePlayback()
findNavController().navigateUp()
}
stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(query: String): Boolean {
handleSearch(query)
return true
}
override fun onQueryTextSubmit(query: String): Boolean {
handleSearch(query)
return true
}
})
return view
}
override fun onDestroy() {
super.onDestroy()
// Stop playback when fragment is destroyed (e.g. via back button)
if (this::searchResultAdapter.isInitialized) {
searchResultAdapter.stopPrePlayback()
}
}
private fun setupRecyclerView() {
searchResultAdapter = SearchResultAdapter(this, listOf())
stationSearchResultList.adapter = searchResultAdapter
stationSearchResultList.layoutManager = LinearLayoutManager(context)
stationSearchResultList.itemAnimator = DefaultItemAnimator()
}
private fun setupSearchView() {
// TV specific: ensure keyboard opens when search view gets focus
stationSearchBoxView.setOnQueryTextFocusChangeListener { v, hasFocus ->
if (hasFocus) {
// Find the internal EditText of the SearchView
val searchEditText = v.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)
if (searchEditText != null) {
searchEditText.requestFocus()
val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT)
}
}
}
// Make the SearchView always expanded and ready for input
stationSearchBoxView.isIconified = false
}
private fun handleSearch(query: String) {
if (query.isEmpty()) {
resetLayout(true)
return
}
showProgressIndicator()
if (query.startsWith("http")) {
directInputCheck.checkStationAddress(requireContext(), query)
} else {
radioBrowserSearch.searchStation(requireContext(), query, Keys.SEARCH_TYPE_BY_KEYWORD)
}
}
private fun addStationAndExit() {
searchResultAdapter.stopPrePlayback()
val currentCollection = collectionViewModel.collectionLiveData.value ?: return
if (station.streamContent.isNotEmpty() && station.streamContent != Keys.MIME_TYPE_UNSUPPORTED) {
CollectionHelper.addStation(requireContext(), currentCollection, station)
findNavController().navigateUp()
} else {
CoroutineScope(IO).launch {
val contentType = NetworkHelper.detectContentType(station.getStreamUri())
station.streamContent = contentType.type
withContext(Main) {
CollectionHelper.addStation(requireContext(), currentCollection, station)
findNavController().navigateUp()
}
}
}
}
override fun onSearchResultTapped(result: Station) {
station = result
activateAddButton()
}
override fun activateAddButton() {
positiveButton.isEnabled = true
}
override fun deactivateAddButton() {
positiveButton.isEnabled = false
}
@SuppressLint("NotifyDataSetChanged")
override fun onRadioBrowserSearchResults(results: Array<RadioBrowserResult>) {
if (results.isNotEmpty()) {
searchResultAdapter.searchResults = results.map { it.toStation() }
searchResultAdapter.notifyDataSetChanged()
resetLayout(false)
} else {
showNoResultsError()
}
}
@SuppressLint("NotifyDataSetChanged")
override fun onDirectInputCheck(stationList: MutableList<Station>) {
if (stationList.isNotEmpty()) {
searchResultAdapter.searchResults = stationList
searchResultAdapter.notifyDataSetChanged()
resetLayout(false)
} else {
showNoResultsError()
}
}
private fun resetLayout(clear: Boolean) {
positiveButton.isEnabled = false
searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isGone = true
if (clear) searchResultAdapter.resetSelection(true)
}
private fun showProgressIndicator() {
searchRequestProgressIndicator.isVisible = true
noSearchResultsTextView.isGone = true
}
private fun showNoResultsError() {
searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isVisible = true
}
}
@@ -0,0 +1,33 @@
package com.michatec.radio
import android.content.Context
import com.google.android.gms.cast.CastMediaControlIntent
import com.google.android.gms.cast.framework.CastOptions
import com.google.android.gms.cast.framework.OptionsProvider
import com.google.android.gms.cast.framework.SessionProvider
import com.google.android.gms.cast.framework.media.CastMediaOptions
import com.google.android.gms.cast.framework.media.NotificationOptions
@Suppress("unused")
class CastOptionsProvider : OptionsProvider {
override fun getCastOptions(context: Context): CastOptions {
val notificationOptions = NotificationOptions.Builder()
.setTargetActivityClassName(MainActivity::class.java.name)
.build()
val mediaOptions = CastMediaOptions.Builder()
.setNotificationOptions(notificationOptions)
.setExpandedControllerActivityClassName(ExpandedControllerActivity::class.java.name)
.build()
return CastOptions.Builder()
.setReceiverApplicationId(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID)
.setResumeSavedSession(true)
.setStopReceiverApplicationWhenEndingSession(true)
.setCastMediaOptions(mediaOptions)
.build()
}
override fun getAdditionalSessionProviders(context: Context): List<SessionProvider>? {
return null
}
}
@@ -0,0 +1,68 @@
package com.michatec.radio
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SeekBarPreference
import com.michatec.radio.helpers.PreferencesHelper
/*
* EqualizerFragment class: Handles audio frequency settings with 10-band EQ
*/
class EqualizerFragment : PreferenceFragmentCompat() {
// EQ band frequencies matching radio.cpp
private val eqFrequencies = arrayOf("31 Hz", "62 Hz", "125 Hz", "250 Hz", "500 Hz", "1 kHz", "2 kHz", "4 kHz", "8 kHz", "16 kHz")
private val eqKeys = arrayOf(
Keys.PREF_EQ_LOW, // Band 0: 31 Hz
Keys.PREF_EQ_BAND_1, // Band 1: 62 Hz
Keys.PREF_EQ_BAND_2, // Band 2: 125 Hz
Keys.PREF_EQ_BAND_3, // Band 3: 250 Hz
Keys.PREF_EQ_BAND_4, // Band 4: 500 Hz
Keys.PREF_EQ_BAND_5, // Band 5: 1 kHz
Keys.PREF_EQ_MID, // Band 6: 2 kHz
Keys.PREF_EQ_BAND_6, // Band 7: 4 kHz
Keys.PREF_EQ_BAND_7, // Band 8: 8 kHz
Keys.PREF_EQ_HIGH // Band 9: 16 kHz
)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.pref_equalizer_title)
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
val context = preferenceManager.context
val screen = preferenceManager.createPreferenceScreen(context)
// Reset Button
val resetPreference = Preference(context)
resetPreference.title = getString(R.string.pref_equalizer_reset_title)
resetPreference.setIcon(R.drawable.ic_refresh_24dp)
resetPreference.setOnPreferenceClickListener {
PreferencesHelper.resetEqualizer()
for (key in eqKeys) {
findPreference<SeekBarPreference>(key)?.value = 0
}
return@setOnPreferenceClickListener true
}
screen.addPreference(resetPreference)
// Create 10-band EQ
for (i in eqKeys.indices) {
val eqBand = SeekBarPreference(context)
eqBand.title = "Equalizer: ${eqFrequencies[i]}"
eqBand.key = eqKeys[i]
eqBand.setIcon(R.drawable.ic_music_note_24dp)
eqBand.min = -12
eqBand.max = 12
eqBand.showSeekBarValue = true
eqBand.setDefaultValue(0)
screen.addPreference(eqBand)
}
preferenceScreen = screen
}
}
@@ -0,0 +1,14 @@
package com.michatec.radio
import android.view.Menu
import com.google.android.gms.cast.framework.CastButtonFactory
import com.google.android.gms.cast.framework.media.widget.ExpandedControllerActivity
class ExpandedControllerActivity : ExpandedControllerActivity() {
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.expanded_controller, menu)
CastButtonFactory.setUpMediaRouteButton(this, menu, R.id.media_route_menu_item)
return true
}
}
+32 -20
View File
@@ -1,17 +1,3 @@
/*
* Keys.kt
* Implements the keys used throughout the app
* This object hosts all keys used to control Radio state
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio package com.michatec.radio
import java.util.* import java.util.*
@@ -41,6 +27,7 @@ object Keys {
const val EXTRA_START_LAST_PLAYED_STATION: String = "START_LAST_PLAYED_STATION" const val EXTRA_START_LAST_PLAYED_STATION: String = "START_LAST_PLAYED_STATION"
const val EXTRA_SLEEP_TIMER_REMAINING: String = "SLEEP_TIMER_REMAINING" const val EXTRA_SLEEP_TIMER_REMAINING: String = "SLEEP_TIMER_REMAINING"
const val EXTRA_METADATA_HISTORY: String = "METADATA_HISTORY" const val EXTRA_METADATA_HISTORY: String = "METADATA_HISTORY"
const val EXTRA_VISUALIZER_DATA: String = "VISUALIZER_DATA"
// arguments // arguments
const val ARG_UPDATE_COLLECTION: String = "ArgUpdateCollection" const val ARG_UPDATE_COLLECTION: String = "ArgUpdateCollection"
@@ -57,10 +44,10 @@ object Keys {
const val CMD_PLAY_STREAM: String = "PLAY_STREAM" const val CMD_PLAY_STREAM: String = "PLAY_STREAM"
const val CMD_REQUEST_SLEEP_TIMER_REMAINING: String = "REQUEST_SLEEP_TIMER_REMAINING" const val CMD_REQUEST_SLEEP_TIMER_REMAINING: String = "REQUEST_SLEEP_TIMER_REMAINING"
const val CMD_REQUEST_METADATA_HISTORY: String = "REQUEST_METADATA_HISTORY" const val CMD_REQUEST_METADATA_HISTORY: String = "REQUEST_METADATA_HISTORY"
const val CMD_GET_VISUALIZER_DATA: String = "GET_VISUALIZER_DATA"
// preferences // preferences
const val PREF_RADIO_BROWSER_API: String = "RADIO_BROWSER_API" const val PREF_RADIO_BROWSER_API: String = "RADIO_BROWSER_API"
const val PREF_ONE_TIME_HOUSEKEEPING_NECESSARY: String = "ONE_TIME_HOUSEKEEPING_NECESSARY_VERSIONCODE_95" // increment to current app version code to trigger housekeeping that runs only once
const val PREF_THEME_SELECTION: String = "THEME_SELECTION" const val PREF_THEME_SELECTION: String = "THEME_SELECTION"
const val PREF_LAST_UPDATE_COLLECTION: String = "LAST_UPDATE_COLLECTION" const val PREF_LAST_UPDATE_COLLECTION: String = "LAST_UPDATE_COLLECTION"
const val PREF_COLLECTION_SIZE: String = "COLLECTION_SIZE" const val PREF_COLLECTION_SIZE: String = "COLLECTION_SIZE"
@@ -75,11 +62,39 @@ object Keys {
const val PREF_LARGE_BUFFER_SIZE: String = "LARGE_BUFFER_SIZE" const val PREF_LARGE_BUFFER_SIZE: String = "LARGE_BUFFER_SIZE"
const val PREF_EDIT_STATIONS: String = "EDIT_STATIONS" const val PREF_EDIT_STATIONS: String = "EDIT_STATIONS"
const val PREF_EDIT_STREAMS_URIS: String = "EDIT_STREAMS_URIS" const val PREF_EDIT_STREAMS_URIS: String = "EDIT_STREAMS_URIS"
const val PREF_BASS_BOOST: String = "BASS_BOOST"
const val PREF_REVERB: String = "REVERB"
const val PREF_DRC: String = "DRC"
const val PREF_EQ_LOW: String = "EQ_LOW"
const val PREF_EQ_MID: String = "EQ_MID"
const val PREF_EQ_HIGH: String = "EQ_HIGH"
const val PREF_EQUALIZER: String = "EQUALIZER_SETTINGS"
const val PREF_EQ_BAND_1: String = "EQ_BAND_1"
const val PREF_EQ_BAND_2: String = "EQ_BAND_2"
const val PREF_EQ_BAND_3: String = "EQ_BAND_3"
const val PREF_EQ_BAND_4: String = "EQ_BAND_4"
const val PREF_EQ_BAND_5: String = "EQ_BAND_5"
const val PREF_EQ_BAND_6: String = "EQ_BAND_6"
const val PREF_EQ_BAND_7: String = "EQ_BAND_7"
const val PREF_PRESET_SELECTED: String = "PRESET_SELECTED"
const val PREF_PRESET_EQ_BAND_0: String = "PRESET_EQ_BAND_0"
const val PREF_PRESET_EQ_BAND_1: String = "PRESET_EQ_BAND_1"
const val PREF_PRESET_EQ_BAND_2: String = "PRESET_EQ_BAND_2"
const val PREF_PRESET_EQ_BAND_3: String = "PRESET_EQ_BAND_3"
const val PREF_PRESET_EQ_BAND_4: String = "PRESET_EQ_BAND_4"
const val PREF_PRESET_EQ_BAND_5: String = "PRESET_EQ_BAND_5"
const val PREF_PRESET_EQ_BAND_6: String = "PRESET_EQ_BAND_6"
const val PREF_PRESET_EQ_BAND_7: String = "PRESET_EQ_BAND_7"
const val PREF_PRESET_EQ_BAND_8: String = "PRESET_EQ_BAND_8"
const val PREF_PRESET_EQ_BAND_9: String = "PRESET_EQ_BAND_9"
const val PREF_PRESET_BASS_BOOST: String = "PRESET_BASS_BOOST"
const val PREF_PRESET_REVERB: String = "PRESET_REVERB"
const val PREF_PRESET_DRC: String = "PRESET_DRC"
const val PREF_PRESET_STEREO_WIDTH: String = "PRESET_STEREO_WIDTH"
// default const values // default const values
const val DEFAULT_SIZE_OF_METADATA_HISTORY: Int = 25 const val DEFAULT_SIZE_OF_METADATA_HISTORY: Int = 25
const val DEFAULT_MAX_LENGTH_OF_METADATA_ENTRY: Int = 127 const val DEFAULT_MAX_LENGTH_OF_METADATA_ENTRY: Int = 127
const val DEFAULT_DOWNLOAD_OVER_MOBILE: Boolean = false
const val ACTIVE_DOWNLOADS_EMPTY: String = "zero" const val ACTIVE_DOWNLOADS_EMPTY: String = "zero"
const val DEFAULT_MAX_RECONNECTION_COUNT: Int = 30 const val DEFAULT_MAX_RECONNECTION_COUNT: Int = 30
const val LARGE_BUFFER_SIZE_MULTIPLIER: Int = 8 const val LARGE_BUFFER_SIZE_MULTIPLIER: Int = 8
@@ -138,7 +153,7 @@ object Keys {
const val FOLDER_AUDIO: String = "audio" const val FOLDER_AUDIO: String = "audio"
const val FOLDER_IMAGES: String = "images" const val FOLDER_IMAGES: String = "images"
const val FOLDER_TEMP: String = "temp" const val FOLDER_TEMP: String = "temp"
const val URLRADIO_LEGACY_FOLDER_COLLECTION: String = "Collection" const val RADIO_LEGACY_FOLDER_COLLECTION: String = "Collection"
// file names and extensions // file names and extensions
const val COLLECTION_FILE: String = "collection.json" const val COLLECTION_FILE: String = "collection.json"
@@ -150,9 +165,6 @@ object Keys {
const val RADIO_BROWSER_API_BASE: String = "all.api.radio-browser.info" const val RADIO_BROWSER_API_BASE: String = "all.api.radio-browser.info"
const val RADIO_BROWSER_API_DEFAULT: String = "de1.api.radio-browser.info" const val RADIO_BROWSER_API_DEFAULT: String = "de1.api.radio-browser.info"
// locations
const val LOCATION_DEFAULT_STATION_IMAGE: String = "android.resource://com.michatec.radio/drawable/ic_default_station_image_24dp"
// sizes (in dp) // sizes (in dp)
const val SIZE_STATION_IMAGE_CARD: Int = 72 const val SIZE_STATION_IMAGE_CARD: Int = 72
const val SIZE_STATION_IMAGE_MAXIMUM: Int = 640 const val SIZE_STATION_IMAGE_MAXIMUM: Int = 640
@@ -1,32 +1,23 @@
/*
* MainActivity.kt
* Implements the MainActivity class
* MainActivity is the default activity that can host the player fragment and the settings fragment
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio package com.michatec.radio
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.core.view.isVisible
import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.navigateUp import androidx.navigation.ui.navigateUp
import com.michatec.radio.helpers.AppThemeHelper import com.michatec.radio.helpers.AppThemeHelper
import com.michatec.radio.helpers.FileHelper import com.michatec.radio.helpers.FileHelper
import com.michatec.radio.helpers.ImportHelper
import com.michatec.radio.helpers.PreferencesHelper import com.michatec.radio.helpers.PreferencesHelper
import org.woheller69.freeDroidWarn.FreeDroidWarn
/* /*
* MainActivity class * MainActivity class
@@ -36,22 +27,14 @@ class MainActivity : AppCompatActivity() {
/* Main class variables */ /* Main class variables */
private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var appBarConfiguration: AppBarConfiguration
/* Overrides onCreate from AppCompatActivity */ /* Overrides onCreate from AppCompatActivity */
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
// house-keeping: determine if edit stations is enabled by default todo: remove in 2023 // Free Android
if (PreferencesHelper.isHouseKeepingNecessary()) { FreeDroidWarn.showWarningOnUpgrade(this, BuildConfig.VERSION_CODE)
// house-keeping 1: remove hard coded default image
ImportHelper.removeDefaultStationImageUris(this)
// house-keeping 2: if existing user detected, enable Edit Stations by default
if (PreferencesHelper.loadCollectionSize() != -1) {
// existing user detected - enable Edit Stations by default
PreferencesHelper.saveEditStationsEnabled(true)
}
PreferencesHelper.saveHouseKeepingNecessaryState()
}
// set up views // set up views
setContentView(R.layout.activity_main) setContentView(R.layout.activity_main)
@@ -62,21 +45,51 @@ class MainActivity : AppCompatActivity() {
// set up action bar // set up action bar
setSupportActionBar(findViewById(R.id.main_toolbar)) setSupportActionBar(findViewById(R.id.main_toolbar))
val toolbar: Toolbar = findViewById(R.id.main_toolbar) val toolbar: Toolbar = findViewById(R.id.main_toolbar)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.main_host_container) as NavHostFragment val navHostFragment =
supportFragmentManager.findFragmentById(R.id.main_host_container) as NavHostFragment
val navController = navHostFragment.navController val navController = navHostFragment.navController
appBarConfiguration = AppBarConfiguration(navController.graph) appBarConfiguration = AppBarConfiguration(navController.graph)
NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration) NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration)
supportActionBar?.hide() supportActionBar?.hide()
// TV-specific loading logic: Hide the overlay once the app is ready
if (packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
Handler(Looper.getMainLooper()).postDelayed({
hideLoadingOverlay()
}, 1200)
} else {
findViewById<View>(R.id.loading_layout)?.visibility = View.GONE
}
// register listener for changes in shared preferences // register listener for changes in shared preferences
PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
} }
/* Hides the loading/splash overlay */
private fun hideLoadingOverlay() {
findViewById<View>(R.id.loading_layout)?.let { overlay ->
if (overlay.isVisible) {
overlay.animate().alpha(0f).setDuration(500)
.withEndAction { overlay.visibility = View.GONE }
}
}
}
/* Overrides onResume from AppCompatActivity */
override fun onResume() {
try {
super.onResume()
} catch (_: ClassCastException) {
// Do nothing
}
}
/* Overrides onSupportNavigateUp from AppCompatActivity */ /* Overrides onSupportNavigateUp from AppCompatActivity */
override fun onSupportNavigateUp(): Boolean { override fun onSupportNavigateUp(): Boolean {
// Taken from: https://developer.android.com/guide/navigation/navigation-ui#action_bar val navHostFragment =
val navHostFragment = supportFragmentManager.findFragmentById(R.id.main_host_container) as NavHostFragment supportFragmentManager.findFragmentById(R.id.main_host_container) as NavHostFragment
val navController = navHostFragment.navController val navController = navHostFragment.navController
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
} }
@@ -1,17 +1,3 @@
/*
* PlayerFragment.kt
* Implements the PlayerFragment class
* PlayerFragment is the fragment that hosts Radio's list of stations and a player sheet
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio package com.michatec.radio
import android.app.Activity import android.app.Activity
@@ -32,17 +18,23 @@ import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import androidx.media3.common.MediaItem import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException import androidx.media3.common.PlaybackException
import androidx.media3.common.Player import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.MediaController import androidx.media3.session.MediaController
import androidx.media3.session.SessionResult import androidx.media3.session.SessionResult
import androidx.media3.session.SessionToken import androidx.media3.session.SessionToken
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request import com.android.volley.Request
@@ -179,9 +171,11 @@ class PlayerFragment : Fragment(),
// hide action bar // hide action bar
(activity as AppCompatActivity).supportActionBar?.hide() (activity as AppCompatActivity).supportActionBar?.hide()
// set the same background color of the player sheet for the navigation bar ViewCompat.setOnApplyWindowInsetsListener(layout.rootView) { v, insets ->
(activity as AppCompatActivity).window.navigationBarColor = ContextCompat.getColor(requireActivity(), R.color.player_sheet_background) val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.updatePadding(bottom = systemBars.bottom)
insets
}
// associate the ItemTouchHelper with the RecyclerView // associate the ItemTouchHelper with the RecyclerView
itemTouchHelper = ItemTouchHelper(ItemTouchHelperCallback()) itemTouchHelper = ItemTouchHelper(ItemTouchHelperCallback())
itemTouchHelper?.attachToRecyclerView(layout.recyclerView) itemTouchHelper?.attachToRecyclerView(layout.recyclerView)
@@ -209,14 +203,14 @@ class PlayerFragment : Fragment(),
} }
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val fromPosition = viewHolder.adapterPosition val fromPosition = viewHolder.bindingAdapterPosition
val toPosition = target.adapterPosition val toPosition = target.bindingAdapterPosition
collectionAdapter.onItemMove(fromPosition, toPosition) collectionAdapter.onItemMove(fromPosition, toPosition)
return true return true
} }
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition val position = viewHolder.bindingAdapterPosition
collectionAdapter.onItemDismiss(position) collectionAdapter.onItemDismiss(position)
} }
@@ -255,7 +249,6 @@ class PlayerFragment : Fragment(),
// load player state // load player state
playerState = PreferencesHelper.loadPlayerState() playerState = PreferencesHelper.loadPlayerState()
// recreate player ui // recreate player ui
// setupPlaybackControls()
updatePlayerViews() updatePlayerViews()
updateStationListState() updateStationListState()
togglePeriodicSleepTimerUpdateRequest() togglePeriodicSleepTimerUpdateRequest()
@@ -263,8 +256,8 @@ class PlayerFragment : Fragment(),
observeCollectionViewModel() observeCollectionViewModel()
// handle navigation arguments // handle navigation arguments
handleNavigationArguments() handleNavigationArguments()
// // handle start intent - if started via tap on rss link // handle start intent - if started via tap on rss link
// handleStartIntent() handleStartIntent()
// start watching for changes in shared preferences // start watching for changes in shared preferences
PreferencesHelper.registerPreferenceChangeListener(this as SharedPreferences.OnSharedPreferenceChangeListener) PreferencesHelper.registerPreferenceChangeListener(this as SharedPreferences.OnSharedPreferenceChangeListener)
} }
@@ -350,8 +343,15 @@ class PlayerFragment : Fragment(),
/* Overrides onAddNewButtonTapped from CollectionAdapterListener */ /* Overrides onAddNewButtonTapped from CollectionAdapterListener */
override fun onAddNewButtonTapped() { override fun onAddNewButtonTapped() {
// stop playback when adding a new station
controller?.stop()
if (activity?.packageManager?.hasSystemFeature(PackageManager.FEATURE_LEANBACK) == true) {
findNavController().navigate(R.id.action_map_fragment_to_player_to_add_station)
} else {
FindStationDialog(activity as Activity, this as FindStationDialog.FindStationDialogListener).show() FindStationDialog(activity as Activity, this as FindStationDialog.FindStationDialogListener).show()
} }
}
/* Overrides onChangeImageButtonTapped from CollectionAdapterListener */ /* Overrides onChangeImageButtonTapped from CollectionAdapterListener */
@@ -395,6 +395,7 @@ class PlayerFragment : Fragment(),
/* Initializes the MediaController - handles connection to PlayerService under the hood */ /* Initializes the MediaController - handles connection to PlayerService under the hood */
@OptIn(UnstableApi::class)
private fun initializeController() { private fun initializeController() {
controllerFuture = MediaController.Builder( controllerFuture = MediaController.Builder(
activity as Context, activity as Context,
@@ -409,6 +410,7 @@ class PlayerFragment : Fragment(),
/* Releases MediaController */ /* Releases MediaController */
private fun releaseController() { private fun releaseController() {
controller?.removeListener(playerListener)
MediaController.releaseFuture(controllerFuture) MediaController.releaseFuture(controllerFuture)
} }
@@ -417,6 +419,13 @@ class PlayerFragment : Fragment(),
private fun setupController() { private fun setupController() {
val controller: MediaController = this.controller ?: return val controller: MediaController = this.controller ?: return
controller.addListener(playerListener) controller.addListener(playerListener)
// Sync local playerState with actual controller state
if (playerState.isPlaying != controller.isPlaying) {
playerState.isPlaying = controller.isPlaying
updatePlayerViews()
}
requestMetadataUpdate() requestMetadataUpdate()
// handle start intent // handle start intent
handleStartIntent() handleStartIntent()
@@ -432,15 +441,15 @@ class PlayerFragment : Fragment(),
val swipeToDeleteHandler = object : UiHelper.SwipeToDeleteCallback(activity as Context) { val swipeToDeleteHandler = object : UiHelper.SwipeToDeleteCallback(activity as Context) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// ask user // ask user
val adapterPosition: Int = viewHolder.adapterPosition val bindingAdapterPosition: Int = viewHolder.bindingAdapterPosition
val dialogMessage = val dialogMessage =
"${getString(R.string.dialog_yes_no_message_remove_station)}\n\n- ${collection.stations[adapterPosition].name}" "${getString(R.string.dialog_yes_no_message_remove_station)}\n\n- ${collection.stations[bindingAdapterPosition].name}"
YesNoDialog(this@PlayerFragment as YesNoDialog.YesNoDialogListener).show( YesNoDialog(this@PlayerFragment as YesNoDialog.YesNoDialogListener).show(
context = activity as Context, context = activity as Context,
type = Keys.DIALOG_REMOVE_STATION, type = Keys.DIALOG_REMOVE_STATION,
messageString = dialogMessage, messageString = dialogMessage,
yesButton = R.string.dialog_yes_no_positive_button_remove_station, yesButton = R.string.dialog_yes_no_positive_button_remove_station,
payload = adapterPosition payload = bindingAdapterPosition
) )
} }
} }
@@ -452,15 +461,15 @@ class PlayerFragment : Fragment(),
object : UiHelper.SwipeToMarkStarredCallback(activity as Context) { object : UiHelper.SwipeToMarkStarredCallback(activity as Context) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// mark card starred // mark card starred
val adapterPosition: Int = viewHolder.adapterPosition val bindingAdapterPosition: Int = viewHolder.bindingAdapterPosition
collectionAdapter.toggleStarredStation(activity as Context, adapterPosition) collectionAdapter.toggleStarredStation(activity as Context, bindingAdapterPosition)
} }
} }
val swipeToMarkStarredItemTouchHelper = ItemTouchHelper(swipeToMarkStarredHandler) val swipeToMarkStarredItemTouchHelper = ItemTouchHelper(swipeToMarkStarredHandler)
swipeToMarkStarredItemTouchHelper.attachToRecyclerView(layout.recyclerView) swipeToMarkStarredItemTouchHelper.attachToRecyclerView(layout.recyclerView)
// set up sleep timer start button // set up sleep timer start button
layout.sheetSleepTimerStartButtonView.setOnClickListener { layout.sheetSleepTimerStartButtonView?.setOnClickListener {
when (controller?.isPlaying) { when (controller?.isPlaying) {
true -> { true -> {
val timePicker = MaterialTimePicker.Builder() val timePicker = MaterialTimePicker.Builder()
@@ -490,29 +499,29 @@ class PlayerFragment : Fragment(),
} }
// set up sleep timer cancel button // set up sleep timer cancel button
layout.sheetSleepTimerCancelButtonView.setOnClickListener { layout.sheetSleepTimerCancelButtonView?.setOnClickListener {
playerState.sleepTimerRunning = false playerState.sleepTimerRunning = false
controller?.cancelSleepTimer() controller?.cancelSleepTimer()
togglePeriodicSleepTimerUpdateRequest() togglePeriodicSleepTimerUpdateRequest()
} }
// set up TV station navigation
layout.playerPrevButtonView?.setOnClickListener {
val currentPosition = CollectionHelper.getStationPosition(collection, playerState.stationUuid)
if (currentPosition > 0) {
val prevStation = collection.stations[currentPosition - 1]
onPlayButtonTapped(prevStation.uuid)
}
}
layout.playerNextButtonView?.setOnClickListener {
val currentPosition = CollectionHelper.getStationPosition(collection, playerState.stationUuid)
if (currentPosition < collection.stations.size - 1) {
val nextStation = collection.stations[currentPosition + 1]
onPlayButtonTapped(nextStation.uuid)
}
} }
}
// /* Sets up the general playback controls - Note: station specific controls and views are updated in updatePlayerViews() */
// // it is probably okay to suppress this warning - the OnTouchListener on the time played view does only toggle the time duration / remaining display
// private fun setupPlaybackControls() {
//
// // main play/pause button
// layout.playButtonView.setOnClickListener {
// onPlayButtonTapped(playerState.stationUuid, playerState.playbackState)
// //onPlayButtonTapped(playerState.stationUuid, playerController.getPlaybackState().state) // todo remove
// }
//
// // register a callback to stay in sync
// playerController.registerCallback(mediaControllerCallback)
// }
/* Sets up the player */ /* Sets up the player */
private fun updatePlayerViews() { private fun updatePlayerViews() {
@@ -549,7 +558,7 @@ class PlayerFragment : Fragment(),
private fun requestSleepTimerUpdate() { private fun requestSleepTimerUpdate() {
val resultFuture: ListenableFuture<SessionResult>? = val resultFuture: ListenableFuture<SessionResult>? =
controller?.requestSleepTimerRemaining() controller?.requestSleepTimerRemaining()
resultFuture?.addListener(Runnable { resultFuture?.addListener({
val timeRemaining: Long = resultFuture.get().extras.getLong(Keys.EXTRA_SLEEP_TIMER_REMAINING) val timeRemaining: Long = resultFuture.get().extras.getLong(Keys.EXTRA_SLEEP_TIMER_REMAINING)
layout.updateSleepTimer(activity as Context, timeRemaining) layout.updateSleepTimer(activity as Context, timeRemaining)
}, MoreExecutors.directExecutor()) }, MoreExecutors.directExecutor())
@@ -559,7 +568,7 @@ class PlayerFragment : Fragment(),
/* Requests an update of the metadata history from the player service */ /* Requests an update of the metadata history from the player service */
private fun requestMetadataUpdate() { private fun requestMetadataUpdate() {
val resultFuture: ListenableFuture<SessionResult>? = controller?.requestMetadataHistory() val resultFuture: ListenableFuture<SessionResult>? = controller?.requestMetadataHistory()
resultFuture?.addListener(Runnable { resultFuture?.addListener({
val metadata: ArrayList<String>? = resultFuture.get().extras.getStringArrayList(Keys.EXTRA_METADATA_HISTORY) val metadata: ArrayList<String>? = resultFuture.get().extras.getStringArrayList(Keys.EXTRA_METADATA_HISTORY)
layout.updateMetadata(metadata?.toMutableList()) layout.updateMetadata(metadata?.toMutableList())
}, MoreExecutors.directExecutor()) }, MoreExecutors.directExecutor())
@@ -573,22 +582,34 @@ class PlayerFragment : Fragment(),
/* Handles this activity's start intent */ /* Handles this activity's start intent */
private fun handleStartIntent() { private fun handleStartIntent() {
if ((activity as Activity).intent.action != null) { val intent = (activity as Activity).intent
when ((activity as Activity).intent.action) { if (intent.action != null && intent.action?.isNotEmpty() == true) {
Keys.ACTION_SHOW_PLAYER -> handleShowPlayer() var handled = false
Intent.ACTION_VIEW -> handleViewIntent() when (intent.action) {
Keys.ACTION_START -> handleStartPlayer() Keys.ACTION_SHOW_PLAYER -> {
handleShowPlayer()
handled = true
}
Intent.ACTION_VIEW -> {
handleViewIntent()
handled = true
}
Keys.ACTION_START -> {
handled = handleStartPlayer()
} }
} }
if (handled) {
// clear intent action to prevent double calls // clear intent action to prevent double calls
(activity as Activity).intent.action = "" intent.action = ""
}
}
} }
/* Handles ACTION_SHOW_PLAYER request from notification */ /* Handles ACTION_SHOW_PLAYER request from notification */
private fun handleShowPlayer() { private fun handleShowPlayer() {
Log.i(TAG, "Tap on notification registered.") Log.i(TAG, "Tap on notification registered.")
// todo implement layout.showPlayer(requireActivity())
} }
@@ -602,16 +623,18 @@ class PlayerFragment : Fragment(),
val scheme: String = intentUri.scheme ?: String() val scheme: String = intentUri.scheme ?: String()
// CASE: intent is a web link // CASE: intent is a web link
if (scheme.startsWith("http")) { if (scheme.startsWith("http")) {
Log.i(TAG, "Transistor was started to handle a web link.") Log.i(TAG, "Radio was started to handle a web link.")
stationList.addAll(CollectionHelper.createStationsFromUrl(intentUri.toString())) stationList.addAll(CollectionHelper.createStationsFromUrl(intentUri.toString()))
} }
// CASE: intent is a local file // CASE: intent is a local file
else if (scheme.startsWith("content")) { else if (scheme.startsWith("content")) {
Log.i(TAG, "Transistor was started to handle a local audio playlist.") Log.i(TAG, "Radio was started to handle a local audio playlist.")
stationList.addAll(CollectionHelper.createStationListFromContentUri(activity as Context, intentUri)) stationList.addAll(CollectionHelper.createStationListFromContentUri(activity as Context, intentUri))
} }
withContext(Main) { withContext(Main) {
if (stationList.isNotEmpty()) { if (stationList.isNotEmpty()) {
// stop playback when adding a new station via intent
controller?.stop()
AddStationDialog(activity as Activity, stationList, this@PlayerFragment as AddStationDialog.AddStationDialogListener).show() AddStationDialog(activity as Activity, stationList, this@PlayerFragment as AddStationDialog.AddStationDialogListener).show()
} else { } else {
// invalid address // invalid address
@@ -624,17 +647,30 @@ class PlayerFragment : Fragment(),
/* Handles START_PLAYER_SERVICE request from App Shortcut */ /* Handles START_PLAYER_SERVICE request from App Shortcut */
private fun handleStartPlayer() { private fun handleStartPlayer(): Boolean {
if (controller == null || collection.stations.isEmpty()) {
return false
}
val intent: Intent = (activity as Activity).intent val intent: Intent = (activity as Activity).intent
if (intent.hasExtra(Keys.EXTRA_START_LAST_PLAYED_STATION)) { if (intent.hasExtra(Keys.EXTRA_START_LAST_PLAYED_STATION)) {
controller?.play(activity as Context, CollectionHelper.getStation(collection, playerState.stationUuid)) val station = CollectionHelper.getStation(collection, playerState.stationUuid)
if (station.isValid()) {
controller?.play(activity as Context, station)
return true
}
} else if (intent.hasExtra(Keys.EXTRA_STATION_UUID)) { } else if (intent.hasExtra(Keys.EXTRA_STATION_UUID)) {
val uuid: String = intent.getStringExtra(Keys.EXTRA_STATION_UUID) ?: String() val uuid: String = intent.getStringExtra(Keys.EXTRA_STATION_UUID) ?: String()
controller?.play(activity as Context, CollectionHelper.getStation(collection, uuid)) val station = CollectionHelper.getStation(collection, uuid)
if (station.isValid()) {
controller?.play(activity as Context, station)
return true
}
} else if (intent.hasExtra(Keys.EXTRA_STREAM_URI)) { } else if (intent.hasExtra(Keys.EXTRA_STREAM_URI)) {
val streamUri: String = intent.getStringExtra(Keys.EXTRA_STREAM_URI) ?: String() val streamUri: String = intent.getStringExtra(Keys.EXTRA_STREAM_URI) ?: String()
controller?.playStreamDirectly(streamUri) controller?.playStreamDirectly(streamUri)
return true
} }
return false
} }
@@ -650,16 +686,16 @@ class PlayerFragment : Fragment(),
collectionViewModel.collectionLiveData.observe(this) { collectionViewModel.collectionLiveData.observe(this) {
// update collection // update collection
collection = it collection = it
//// // updates current station in player views // updates current station in player views
//// playerState = PreferencesHelper.loadPlayerState() playerState = PreferencesHelper.loadPlayerState()
// // get station // get station
// val station: Station = CollectionHelper.getStation(collection, playerState.stationUuid) val station: Station = CollectionHelper.getStation(collection, playerState.stationUuid)
// // update player views // update player views
// layout.updatePlayerViews(activity as Context, station, playerState.isPlaying) layout.updatePlayerViews(activity as Context, station, playerState.isPlaying)
//// // handle start intent // handle start intent
//// handleStartIntent() handleStartIntent()
//// // handle navigation arguments // handle navigation arguments
//// handleNavigationArguments() handleNavigationArguments()
} }
collectionViewModel.collectionSizeLiveData.observe(this) { collectionViewModel.collectionSizeLiveData.observe(this) {
// size of collection changed // size of collection changed
@@ -754,6 +790,7 @@ class PlayerFragment : Fragment(),
layout.showBufferingIndicator(buffering = false) layout.showBufferingIndicator(buffering = false)
} else { } else {
// playback is paused or stopped // playback is paused or stopped
layout.updateSleepTimer(activity as Context, 0L)
// check if buffering (playback is not active but playWhenReady is true) // check if buffering (playback is not active but playWhenReady is true)
if (controller?.playWhenReady == true) { if (controller?.playWhenReady == true) {
// playback is buffering, show the buffering indicator // playback is buffering, show the buffering indicator
@@ -783,7 +820,7 @@ class PlayerFragment : Fragment(),
/* /*
* Check for update on github * Check for update on GitHub
*/ */
private fun checkForUpdates() { private fun checkForUpdates() {
val url = getString(R.string.snackbar_github_update_check_url) val url = getString(R.string.snackbar_github_update_check_url)
@@ -801,7 +838,7 @@ class PlayerFragment : Fragment(),
.setAction(R.string.snackbar_show) { .setAction(R.string.snackbar_show) {
val releaseurl = getString(R.string.snackbar_url_app_home_page) val releaseurl = getString(R.string.snackbar_url_app_home_page)
val i = Intent(Intent.ACTION_VIEW) val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(releaseurl) i.data = releaseurl.toUri()
// Not sure that does anything // Not sure that does anything
i.putExtra("SOURCE", "SELF") i.putExtra("SOURCE", "SELF")
startActivity(i) startActivity(i)
@@ -820,9 +857,4 @@ class PlayerFragment : Fragment(),
request.tag = TAG request.tag = TAG
queue.add(request) queue.add(request)
} }
/*
* End of declaration
*/
} }
@@ -1,17 +1,3 @@
/*
* PlayerService.kt
* Implements the PlayerService class
* PlayerService is Radio's foreground service that plays radio station audio
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio package com.michatec.radio
import android.app.PendingIntent import android.app.PendingIntent
@@ -24,12 +10,16 @@ import android.os.CountDownTimer
import android.util.Log import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.media.MediaBrowserServiceCompat.BrowserRoot.EXTRA_RECENT import androidx.media.MediaBrowserServiceCompat.BrowserRoot.EXTRA_RECENT
import androidx.media3.cast.CastPlayer
import androidx.media3.common.* import androidx.media3.common.*
import androidx.media3.common.util.UnstableApi import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.HttpDataSource import androidx.media3.datasource.HttpDataSource
import androidx.media3.exoplayer.DefaultLoadControl import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.analytics.AnalyticsListener import androidx.media3.exoplayer.analytics.AnalyticsListener
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.exoplayer.upstream.DefaultAllocator import androidx.media3.exoplayer.upstream.DefaultAllocator
import androidx.media3.exoplayer.upstream.DefaultLoadErrorHandlingPolicy import androidx.media3.exoplayer.upstream.DefaultLoadErrorHandlingPolicy
@@ -39,10 +29,7 @@ import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture import com.google.common.util.concurrent.ListenableFuture
import com.michatec.radio.core.Collection import com.michatec.radio.core.Collection
import com.michatec.radio.helpers.AudioHelper import com.michatec.radio.helpers.*
import com.michatec.radio.helpers.CollectionHelper
import com.michatec.radio.helpers.FileHelper
import com.michatec.radio.helpers.PreferencesHelper
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import java.util.* import java.util.*
@@ -52,13 +39,15 @@ import java.util.*
* PlayerService class * PlayerService class
*/ */
@UnstableApi @UnstableApi
class PlayerService : MediaLibraryService() { class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenceChangeListener {
/* Define log tag */ /* Define log tag */
private val TAG: String = PlayerService::class.java.simpleName private val TAG: String = PlayerService::class.java.simpleName
/* Main class variables */ /* Main class variables */
private lateinit var player: Player private lateinit var player: Player
private lateinit var exoPlayer: ExoPlayer
private lateinit var castPlayer: CastPlayer
private lateinit var mediaLibrarySession: MediaLibrarySession private lateinit var mediaLibrarySession: MediaLibrarySession
private lateinit var sleepTimer: CountDownTimer private lateinit var sleepTimer: CountDownTimer
var sleepTimerTimeRemaining: Long = 0L var sleepTimerTimeRemaining: Long = 0L
@@ -71,6 +60,9 @@ class PlayerService : MediaLibraryService() {
private var playLastStation: Boolean = false private var playLastStation: Boolean = false
private var manuallyCancelledSleepTimer = false private var manuallyCancelledSleepTimer = false
// Native Audio Processor instance
private val nativeAudioProcessor = NativeAudioProcessor()
/* Overrides onCreate from Service */ /* Overrides onCreate from Service */
override fun onCreate() { override fun onCreate() {
@@ -90,15 +82,25 @@ class PlayerService : MediaLibraryService() {
setMediaNotificationProvider(notificationProvider) setMediaNotificationProvider(notificationProvider)
// fetch the metadata history // fetch the metadata history
metadataHistory = PreferencesHelper.loadMetadataHistory() metadataHistory = PreferencesHelper.loadMetadataHistory()
// register preference change listener
PreferencesHelper.registerPreferenceChangeListener(this)
// apply initial audio effects
applyAudioEffects()
} }
/* Overrides onDestroy from Service */ /* Overrides onDestroy from Service */
override fun onDestroy() { override fun onDestroy() {
// player.removeAnalyticsListener(analyticsListener) // Reset playing state in preferences
PreferencesHelper.saveIsPlaying(false)
player.removeListener(playerListener) player.removeListener(playerListener)
player.release() player.release()
exoPlayer.release()
castPlayer.release()
mediaLibrarySession.release() mediaLibrarySession.release()
// unregister preference change listener
PreferencesHelper.unregisterPreferenceChangeListener(this)
super.onDestroy() super.onDestroy()
} }
@@ -119,8 +121,26 @@ class PlayerService : MediaLibraryService() {
/* Initializes the ExoPlayer */ /* Initializes the ExoPlayer */
private fun initializePlayer() { private fun initializePlayer() {
val exoPlayer: ExoPlayer = ExoPlayer.Builder(this).apply { val audioAttributes = AudioAttributes.Builder()
setAudioAttributes(AudioAttributes.DEFAULT, true) .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_MEDIA)
.build()
// Create a RenderersFactory that injects the NativeAudioProcessor
val renderersFactory = object : DefaultRenderersFactory(this) {
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean
): AudioSink? {
return DefaultAudioSink.Builder(context)
.setAudioProcessors(arrayOf(nativeAudioProcessor))
.build()
}
}
exoPlayer = ExoPlayer.Builder(this, renderersFactory).apply {
setAudioAttributes(audioAttributes, true)
setHandleAudioBecomingNoisy(true) setHandleAudioBecomingNoisy(true)
setLoadControl(createDefaultLoadControl(bufferSizeMultiplier)) setLoadControl(createDefaultLoadControl(bufferSizeMultiplier))
setMediaSourceFactory( setMediaSourceFactory(
@@ -132,8 +152,12 @@ class PlayerService : MediaLibraryService() {
exoPlayer.addAnalyticsListener(analyticsListener) exoPlayer.addAnalyticsListener(analyticsListener)
exoPlayer.addListener(playerListener) exoPlayer.addListener(playerListener)
// manually add seek to next and seek to previous since headphones issue them and they are translated to next and previous station // Initialize CastPlayer
player = object : ForwardingPlayer(exoPlayer) { castPlayer = CastPlayer.Builder(this).setLocalPlayer(exoPlayer).build()
// manually add seek to next and seek to previous since headphones issue them, and they are translated to next and previous station
// IMPORTANT: Use castPlayer here instead of exoPlayer so the session controls both local and remote playback
player = object : ForwardingPlayer(castPlayer) {
override fun getAvailableCommands(): Player.Commands { override fun getAvailableCommands(): Player.Commands {
return super.getAvailableCommands().buildUpon().add(COMMAND_SEEK_TO_NEXT) return super.getAvailableCommands().buildUpon().add(COMMAND_SEEK_TO_NEXT)
.add(COMMAND_SEEK_TO_PREVIOUS).build() .add(COMMAND_SEEK_TO_PREVIOUS).build()
@@ -147,6 +171,7 @@ class PlayerService : MediaLibraryService() {
return C.TIME_UNSET // this will hide progress bar for HLS stations in the notification return C.TIME_UNSET // this will hide progress bar for HLS stations in the notification
} }
} }
player.addListener(playerListener)
} }
@@ -210,12 +235,9 @@ class PlayerService : MediaLibraryService() {
/* Cancels sleep timer */ /* Cancels sleep timer */
private fun cancelSleepTimer() { private fun cancelSleepTimer() {
if (this::sleepTimer.isInitialized) { if (this::sleepTimer.isInitialized) {
if (manuallyCancelledSleepTimer) {
sleepTimerTimeRemaining = 0L
sleepTimer.cancel() sleepTimer.cancel()
} }
manuallyCancelledSleepTimer = false sleepTimerTimeRemaining = 0L
}
// store timer state // store timer state
PreferencesHelper.saveSleepTimerRunning(isRunning = false) PreferencesHelper.saveSleepTimerRunning(isRunning = false)
} }
@@ -258,11 +280,69 @@ class PlayerService : MediaLibraryService() {
async(Dispatchers.Default) { FileHelper.readCollectionSuspended(context) } async(Dispatchers.Default) { FileHelper.readCollectionSuspended(context) }
// wait for result and update collection // wait for result and update collection
collection = deferred.await() collection = deferred.await()
// // special case: trigger metadata view update for stations that have no metadata }
// if (player.isPlaying && station.name == getCurrentMetadata()) { }
// station = CollectionHelper.getStation(collection, station.uuid)
// updateMetadata(null)
// } /* Applies audio effects based on preferences */
private fun applyAudioEffects() {
val selectedPreset = PreferencesHelper.loadSelectedPreset()
if (selectedPreset.isNotEmpty()) {
applyPreset(selectedPreset)
} else {
// Apply manual settings
nativeAudioProcessor.enableBassBoost(PreferencesHelper.loadBassBoost())
nativeAudioProcessor.setReverb(PreferencesHelper.loadReverb())
nativeAudioProcessor.enableDrc(PreferencesHelper.loadDrcEnabled())
nativeAudioProcessor.setWidth(1f)
// Apply all 10 EQ bands
val eqGains = FloatArray(10)
for (i in 0 until 10) {
eqGains[i] = PreferencesHelper.loadEqBand(i).toFloat()
}
nativeAudioProcessor.setEqAll(eqGains)
}
}
/* Applies a saved preset */
private fun applyPreset(presetName: String) {
when (presetName) {
getString(R.string.pref_preset_rock) -> nativeAudioProcessor.setPresetRock()
getString(R.string.pref_preset_pop) -> nativeAudioProcessor.setPresetPop()
getString(R.string.pref_preset_jazz) -> nativeAudioProcessor.setPresetJazz()
getString(R.string.pref_preset_flat) -> nativeAudioProcessor.setPresetFlat()
else -> {
// Custom preset - load from preferences
nativeAudioProcessor.enableDrc(PreferencesHelper.loadPresetDrc())
nativeAudioProcessor.setReverb(PreferencesHelper.loadPresetReverb())
nativeAudioProcessor.setWidth(PreferencesHelper.loadPresetStereoWidth())
nativeAudioProcessor.enableBassBoost(PreferencesHelper.loadPresetBassBoost())
val eqGains = FloatArray(10)
for (i in 0 until 10) {
eqGains[i] = PreferencesHelper.loadPresetEqBand(i).toFloat()
}
nativeAudioProcessor.setEqAll(eqGains)
}
}
}
/* Overrides onSharedPreferenceChanged from SharedPreferences.OnSharedPreferenceChangeListener */
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
when (key) {
Keys.PREF_BASS_BOOST, Keys.PREF_REVERB, Keys.PREF_DRC,
Keys.PREF_EQ_LOW, Keys.PREF_EQ_MID, Keys.PREF_EQ_HIGH,
Keys.PREF_EQ_BAND_1, Keys.PREF_EQ_BAND_2, Keys.PREF_EQ_BAND_3,
Keys.PREF_EQ_BAND_4, Keys.PREF_EQ_BAND_5, Keys.PREF_EQ_BAND_6,
Keys.PREF_EQ_BAND_7,
Keys.PREF_PRESET_SELECTED,
Keys.PREF_PRESET_EQ_BAND_0, Keys.PREF_PRESET_EQ_BAND_1, Keys.PREF_PRESET_EQ_BAND_2,
Keys.PREF_PRESET_EQ_BAND_3, Keys.PREF_PRESET_EQ_BAND_4, Keys.PREF_PRESET_EQ_BAND_5,
Keys.PREF_PRESET_EQ_BAND_6, Keys.PREF_PRESET_EQ_BAND_7, Keys.PREF_PRESET_EQ_BAND_8,
Keys.PREF_PRESET_EQ_BAND_9,
Keys.PREF_PRESET_BASS_BOOST, Keys.PREF_PRESET_REVERB,
Keys.PREF_PRESET_DRC, Keys.PREF_PRESET_STEREO_WIDTH -> {
applyAudioEffects()
}
} }
} }
@@ -280,19 +360,8 @@ class PlayerService : MediaLibraryService() {
val updatedMediaItems: List<MediaItem> = val updatedMediaItems: List<MediaItem> =
mediaItems.map { mediaItem -> mediaItems.map { mediaItem ->
CollectionHelper.getItem(this@PlayerService, collection, mediaItem.mediaId) CollectionHelper.getItem(this@PlayerService, collection, mediaItem.mediaId)
// if (mediaItem.requestMetadata.searchQuery != null)
// getMediaItemFromSearchQuery(mediaItem.requestMetadata.searchQuery!!)
// else MediaItemTree.getItem(mediaItem.mediaId) ?: mediaItem
} }
return Futures.immediateFuture(updatedMediaItems) return Futures.immediateFuture(updatedMediaItems)
// val updatedMediaItems = mediaItems.map { mediaItem ->
// mediaItem.buildUpon().apply {
// setUri(mediaItem.requestMetadata.mediaUri)
// }.build()
// }
// return Futures.immediateFuture(updatedMediaItems)
} }
@@ -300,13 +369,13 @@ class PlayerService : MediaLibraryService() {
session: MediaSession, session: MediaSession,
controller: MediaSession.ControllerInfo controller: MediaSession.ControllerInfo
): MediaSession.ConnectionResult { ): MediaSession.ConnectionResult {
// add custom commands
val connectionResult: MediaSession.ConnectionResult = super.onConnect(session, controller) val connectionResult: MediaSession.ConnectionResult = super.onConnect(session, controller)
val builder: SessionCommands.Builder = connectionResult.availableSessionCommands.buildUpon() val builder: SessionCommands.Builder = connectionResult.availableSessionCommands.buildUpon()
builder.add(SessionCommand(Keys.CMD_START_SLEEP_TIMER, Bundle.EMPTY)) builder.add(SessionCommand(Keys.CMD_START_SLEEP_TIMER, Bundle.EMPTY))
builder.add(SessionCommand(Keys.CMD_CANCEL_SLEEP_TIMER, Bundle.EMPTY)) builder.add(SessionCommand(Keys.CMD_CANCEL_SLEEP_TIMER, Bundle.EMPTY))
builder.add(SessionCommand(Keys.CMD_REQUEST_SLEEP_TIMER_REMAINING, Bundle.EMPTY)) builder.add(SessionCommand(Keys.CMD_REQUEST_SLEEP_TIMER_REMAINING, Bundle.EMPTY))
builder.add(SessionCommand(Keys.CMD_REQUEST_METADATA_HISTORY, Bundle.EMPTY)) builder.add(SessionCommand(Keys.CMD_REQUEST_METADATA_HISTORY, Bundle.EMPTY))
builder.add(SessionCommand(Keys.CMD_GET_VISUALIZER_DATA, Bundle.EMPTY))
return MediaSession.ConnectionResult.accept(builder.build(), connectionResult.availablePlayerCommands) return MediaSession.ConnectionResult.accept(builder.build(), connectionResult.availablePlayerCommands)
} }
@@ -393,79 +462,23 @@ class PlayerService : MediaLibraryService() {
) )
) )
} }
Keys.CMD_GET_VISUALIZER_DATA -> {
val resultBundle = Bundle()
resultBundle.putFloatArray(
Keys.EXTRA_VISUALIZER_DATA,
nativeAudioProcessor.getVisualizer()
)
return Futures.immediateFuture(
SessionResult(
SessionResult.RESULT_SUCCESS,
resultBundle
)
)
}
} }
return super.onCustomCommand(session, controller, customCommand, args) return super.onCustomCommand(session, controller, customCommand, args)
} }
override fun onPlayerCommandRequest(
session: MediaSession,
controller: MediaSession.ControllerInfo,
playerCommand: Int
): Int {
// playerCommand = one of COMMAND_PLAY_PAUSE, COMMAND_PREPARE, COMMAND_STOP, COMMAND_SEEK_TO_DEFAULT_POSITION, COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM, COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM, COMMAND_SEEK_TO_PREVIOUS, COMMAND_SEEK_TO_NEXT_MEDIA_ITEM, COMMAND_SEEK_TO_NEXT, COMMAND_SEEK_TO_MEDIA_ITEM, COMMAND_SEEK_BACK, COMMAND_SEEK_FORWARD, COMMAND_SET_SPEED_AND_PITCH, COMMAND_SET_SHUFFLE_MODE, COMMAND_SET_REPEAT_MODE, COMMAND_GET_CURRENT_MEDIA_ITEM, COMMAND_GET_TIMELINE, COMMAND_GET_MEDIA_ITEMS_METADATA, COMMAND_SET_MEDIA_ITEMS_METADATA, COMMAND_CHANGE_MEDIA_ITEMS, COMMAND_GET_AUDIO_ATTRIBUTES, COMMAND_GET_VOLUME, COMMAND_GET_DEVICE_VOLUME, COMMAND_SET_VOLUME, COMMAND_SET_DEVICE_VOLUME, COMMAND_ADJUST_DEVICE_VOLUME, COMMAND_SET_VIDEO_SURFACE, COMMAND_GET_TEXT, COMMAND_SET_TRACK_SELECTION_PARAMETERS or COMMAND_GET_TRACK_INFOS. */
// emulate headphone buttons
// start/pause: adb shell input keyevent 85
// next: adb shell input keyevent 87
// prev: adb shell input keyevent 88
when (playerCommand) {
Player.COMMAND_SEEK_TO_NEXT -> {
player.addMediaItem(
CollectionHelper.getNextMediaItem(
this@PlayerService,
collection,
player.currentMediaItem?.mediaId ?: String()
)
)
player.prepare()
player.play()
return SessionResult.RESULT_SUCCESS
}
Player.COMMAND_SEEK_TO_PREVIOUS -> {
player.addMediaItem(
CollectionHelper.getPreviousMediaItem(
this@PlayerService,
collection,
player.currentMediaItem?.mediaId ?: String()
)
)
player.prepare()
player.play()
return SessionResult.RESULT_SUCCESS
}
Player.COMMAND_PREPARE -> {
return if (playLastStation) {
// special case: system requested media resumption (see also onGetLibraryRoot)
player.addMediaItem(CollectionHelper.getRecent(this@PlayerService, collection))
player.prepare()
playLastStation = false
SessionResult.RESULT_SUCCESS
} else {
super.onPlayerCommandRequest(session, controller, playerCommand)
}
}
Player.COMMAND_PLAY_PAUSE -> {
return if (player.isPlaying) {
super.onPlayerCommandRequest(session, controller, playerCommand)
} else {
// seek to the start of the "live window"
player.seekTo(0)
SessionResult.RESULT_SUCCESS
}
}
// Player.COMMAND_PLAY_PAUSE -> {
// // override pause with stop, to prevent unnecessary buffering
// if (player.isPlaying) {
// player.stop()
// return SessionResult.RESULT_INFO_SKIPPED
// } else {
// return super.onPlayerCommandRequest(session, controller, playerCommand)
// }
// }
else -> {
return super.onPlayerCommandRequest(session, controller, playerCommand)
}
}
}
} }
@@ -480,21 +493,21 @@ class PlayerService : MediaLibraryService() {
customLayout: ImmutableList<CommandButton>, customLayout: ImmutableList<CommandButton>,
showPauseButton: Boolean showPauseButton: Boolean
): ImmutableList<CommandButton> { ): ImmutableList<CommandButton> {
val seekToPreviousCommandButton = CommandButton.Builder().apply { val seekToPreviousCommandButton = CommandButton.Builder(CommandButton.ICON_UNDEFINED)
setPlayerCommand(Player.COMMAND_SEEK_TO_PREVIOUS) .setPlayerCommand(Player.COMMAND_SEEK_TO_PREVIOUS)
setIconResId(R.drawable.ic_notification_skip_to_previous_36dp) .setCustomIconResId(R.drawable.ic_notification_skip_to_previous_36dp)
setEnabled(true) .setEnabled(true)
}.build() .build()
val playCommandButton = CommandButton.Builder().apply { val playCommandButton = CommandButton.Builder(CommandButton.ICON_UNDEFINED)
setPlayerCommand(Player.COMMAND_PLAY_PAUSE) .setPlayerCommand(Player.COMMAND_PLAY_PAUSE)
setIconResId(if (player.isPlaying) R.drawable.ic_notification_stop_36dp else R.drawable.ic_notification_play_36dp) .setCustomIconResId(if (player.isPlaying) R.drawable.ic_notification_stop_36dp else R.drawable.ic_notification_play_36dp)
setEnabled(true) .setEnabled(true)
}.build() .build()
val seekToNextCommandButton = CommandButton.Builder().apply { val seekToNextCommandButton = CommandButton.Builder(CommandButton.ICON_UNDEFINED)
setPlayerCommand(Player.COMMAND_SEEK_TO_NEXT) .setPlayerCommand(Player.COMMAND_SEEK_TO_NEXT)
setIconResId(R.drawable.ic_notification_skip_to_next_36dp) .setCustomIconResId(R.drawable.ic_notification_skip_to_next_36dp)
setEnabled(true) .setEnabled(true)
}.build() .build()
val commandButtons: MutableList<CommandButton> = mutableListOf( val commandButtons: MutableList<CommandButton> = mutableListOf(
seekToPreviousCommandButton, seekToPreviousCommandButton,
playCommandButton, playCommandButton,
@@ -526,37 +539,24 @@ class PlayerService : MediaLibraryService() {
currentMediaId, currentMediaId,
isPlaying isPlaying
) )
//updatePlayerState(station, playbackState)
if (isPlaying) { if (!isPlaying) {
// playback is active
} else {
// cancel sleep timer // cancel sleep timer
cancelSleepTimer() cancelSleepTimer()
// reset metadata // reset metadata
updateMetadata() updateMetadata()
// playback is not active // Check playback state to decide whether to stop the service
// Not playing because playback is paused, ended, suppressed, or the player
// is buffering, stopped or failed. Check player.getPlayWhenReady,
// player.getPlaybackState, player.getPlaybackSuppressionReason and
// player.getPlaybackError for details.
when (player.playbackState) { when (player.playbackState) {
// player is able to immediately play from its current position Player.STATE_ENDED, Player.STATE_IDLE -> {
stopSelf()
}
Player.STATE_READY -> { Player.STATE_READY -> {
// todo // Playback is paused. For radio, we can stop the service to remove the notification.
stopSelf()
} }
// buffering - data needs to be loaded
Player.STATE_BUFFERING -> { Player.STATE_BUFFERING -> {
// todo // DO NOT stop the service while buffering (especially important for Cast)
}
// player finished playing all media
Player.STATE_ENDED -> {
// todo
}
// initial state or player is stopped or playback failed
Player.STATE_IDLE -> {
// todo
} }
} }
} }
@@ -565,18 +565,9 @@ class PlayerService : MediaLibraryService() {
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
super.onPlayWhenReadyChanged(playWhenReady, reason) super.onPlayWhenReadyChanged(playWhenReady, reason)
if (!playWhenReady) { if (!playWhenReady) {
when (reason) { // Only stop if not buffering and not ready to play (i.e. truly stopped/paused)
Player.PLAY_WHEN_READY_CHANGE_REASON_END_OF_MEDIA_ITEM -> { if (player.playbackState != Player.STATE_BUFFERING) {
// playback reached end: stop / end playback stopSelf()
}
else -> {
// playback has been paused by user or OS: update media session and save state
// PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST or
// PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS or
// PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY or
// PLAY_WHEN_READY_CHANGE_REASON_REMOTE
// handlePlaybackChange(PlaybackStateCompat.STATE_PAUSED)
}
} }
} }
} }
@@ -585,7 +576,10 @@ class PlayerService : MediaLibraryService() {
override fun onPlayerError(error: PlaybackException) { override fun onPlayerError(error: PlaybackException) {
super.onPlayerError(error) super.onPlayerError(error)
Log.d(TAG, "PlayerError occurred: ${error.errorCodeName}") Log.d(TAG, "PlayerError occurred: ${error.errorCodeName}")
// todo: test if playback needs to be restarted if (error.errorCode == PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED || error.errorCode == PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT) {
player.prepare()
player.play()
}
} }
@@ -598,17 +592,13 @@ class PlayerService : MediaLibraryService() {
/* /*
* Custom LoadErrorHandlingPolicy that network drop outs * Custom LoadErrorHandlingPolicy that network drop-outs
*/ */
private val loadErrorHandlingPolicy: DefaultLoadErrorHandlingPolicy = object: DefaultLoadErrorHandlingPolicy() { private val loadErrorHandlingPolicy: DefaultLoadErrorHandlingPolicy = object: DefaultLoadErrorHandlingPolicy() {
override fun getRetryDelayMsFor(loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo): Long { override fun getRetryDelayMsFor(loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo): Long {
// try to reconnect every 5 seconds - up to 20 times // try to reconnect every 5 seconds - up to 20 times
if (loadErrorInfo.errorCount <= Keys.DEFAULT_MAX_RECONNECTION_COUNT && loadErrorInfo.exception is HttpDataSource.HttpDataSourceException) { if (loadErrorInfo.errorCount <= Keys.DEFAULT_MAX_RECONNECTION_COUNT && loadErrorInfo.exception is HttpDataSource.HttpDataSourceException) {
return Keys.RECONNECTION_WAIT_INTERVAL return Keys.RECONNECTION_WAIT_INTERVAL
// } else {
// CoroutineScope(Main).launch {
// player.stop()
// }
} }
return C.TIME_UNSET return C.TIME_UNSET
} }
@@ -636,22 +626,6 @@ class PlayerService : MediaLibraryService() {
} }
/*
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) {
Keys.PREF_LARGE_BUFFER_SIZE -> {
bufferSizeMultiplier = PreferencesHelper.loadBufferSizeMultiplier()
if (!player.isPlaying && !player.isLoading) {
initializePlayer()
}
}
}
}
/* /*
* Custom AnalyticsListener that enables AudioFX equalizer integration * Custom AnalyticsListener that enables AudioFX equalizer integration
*/ */
@@ -667,7 +641,6 @@ class PlayerService : MediaLibraryService() {
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, packageName) intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, packageName)
intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC) intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC)
sendBroadcast(intent) sendBroadcast(intent)
// note: remember to broadcast AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION, when not needed anymore
} }
} }
} }
@@ -1,17 +1,3 @@
/*
* Radio.kt
* Implements the Radio class
* Radio is the base Application class that sets up day and night theme
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio package com.michatec.radio
import android.app.Application import android.app.Application
@@ -25,8 +11,6 @@ import com.michatec.radio.helpers.PreferencesHelper.initPreferences
*/ */
class Radio : Application() { class Radio : Application() {
/* Define log tag */
private val TAG: String = Radio::class.java.simpleName
/* Implements onCreate */ /* Implements onCreate */
override fun onCreate() { override fun onCreate() {
@@ -36,10 +20,4 @@ class Radio : Application() {
AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection()) AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection())
} }
/* Implements onTerminate */
override fun onTerminate() {
super.onTerminate()
}
} }
@@ -1,17 +1,3 @@
/*
* SettingsFragment.kt
* Implements the SettingsFragment fragment
* A SettingsFragment displays the user accessible settings of the app
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio package com.michatec.radio
import android.app.Activity import android.app.Activity
@@ -20,24 +6,21 @@ import android.content.ClipboardManager
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.view.View import android.view.View
import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.preference.* import androidx.preference.*
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
import com.michatec.radio.dialogs.ErrorDialog import com.michatec.radio.dialogs.ErrorDialog
import com.michatec.radio.dialogs.PresetSelectionDialog
import com.michatec.radio.dialogs.ThemeSelectionDialog
import com.michatec.radio.dialogs.YesNoDialog import com.michatec.radio.dialogs.YesNoDialog
import com.michatec.radio.helpers.* import com.michatec.radio.helpers.*
import com.michatec.radio.helpers.AppThemeHelper.getColor
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -48,7 +31,7 @@ import java.util.*
/* /*
* SettingsFragment class * SettingsFragment class
*/ */
class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogListener { class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogListener, ThemeSelectionDialog.ThemeSelectionDialogListener, PresetSelectionDialog.PresetSelectionDialogListener {
/* Define log tag */ /* Define log tag */
@@ -62,20 +45,6 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
(activity as AppCompatActivity).supportActionBar?.show() (activity as AppCompatActivity).supportActionBar?.show()
(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true) (activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.fragment_settings_title) (activity as AppCompatActivity).supportActionBar?.title = getString(R.string.fragment_settings_title)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// above Android Oreo
(activity as AppCompatActivity).window.navigationBarColor = getColor(requireContext(), android.R.attr.colorBackground)
} else {
val nightMode = AppCompatDelegate.getDefaultNightMode()
if (nightMode == AppCompatDelegate.MODE_NIGHT_YES) {
// night mode is active, set navigation bar color to a suitable color for night mode
(activity as AppCompatActivity).window.navigationBarColor = getColor(requireContext(), android.R.attr.colorBackground)
} else {
// night mode is not active, set navigation bar color to a suitable color for day mode
(activity as AppCompatActivity).window.navigationBarColor = ContextCompat.getColor(requireContext(), android.R.color.black)
}
}
} }
/* Overrides onCreatePreferences from PreferenceFragmentCompat */ /* Overrides onCreatePreferences from PreferenceFragmentCompat */
@@ -84,34 +53,21 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
val context = preferenceManager.context val context = preferenceManager.context
val screen = preferenceManager.createPreferenceScreen(context) val screen = preferenceManager.createPreferenceScreen(context)
// Load current preset once
val currentPreset = PreferencesHelper.loadSelectedPreset()
// set up "App Theme" preference // set up "App Theme" preference
val preferenceThemeSelection = ListPreference(activity as Context) val preferenceThemeSelection = Preference(activity as Context)
preferenceThemeSelection.title = getString(R.string.pref_theme_selection_title) preferenceThemeSelection.title = getString(R.string.pref_theme_selection_title)
preferenceThemeSelection.setIcon(R.drawable.ic_brush_24dp) preferenceThemeSelection.setIcon(R.drawable.ic_brush_24dp)
preferenceThemeSelection.key = Keys.PREF_THEME_SELECTION preferenceThemeSelection.key = Keys.PREF_THEME_SELECTION
preferenceThemeSelection.summary = "${getString(R.string.pref_theme_selection_summary)} ${ preferenceThemeSelection.summary = "${getString(R.string.pref_theme_selection_summary)} ${
AppThemeHelper.getCurrentTheme(activity as Context) AppThemeHelper.getCurrentTheme(activity as Context)
}" }"
preferenceThemeSelection.entries = arrayOf( preferenceThemeSelection.setOnPreferenceClickListener {
getString(R.string.pref_theme_selection_mode_device_default), // show theme selection dialog
getString(R.string.pref_theme_selection_mode_light), ThemeSelectionDialog(this).show(activity as Context)
getString(R.string.pref_theme_selection_mode_dark) return@setOnPreferenceClickListener true
)
preferenceThemeSelection.entryValues = arrayOf(
Keys.STATE_THEME_FOLLOW_SYSTEM,
Keys.STATE_THEME_LIGHT_MODE,
Keys.STATE_THEME_DARK_MODE
)
preferenceThemeSelection.setDefaultValue(Keys.STATE_THEME_FOLLOW_SYSTEM)
preferenceThemeSelection.setOnPreferenceChangeListener { preference, newValue ->
if (preference is ListPreference) {
val index: Int = preference.entryValues.indexOf(newValue)
preferenceThemeSelection.summary =
"${getString(R.string.pref_theme_selection_summary)} ${preference.entries[index]}"
return@setOnPreferenceChangeListener true
} else {
return@setOnPreferenceChangeListener false
}
} }
// set up "Update Station Images" preference // set up "Update Station Images" preference
@@ -130,17 +86,21 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
return@setOnPreferenceClickListener true return@setOnPreferenceClickListener true
} }
// set up "Update Stations" preference
// // set up "Update Stations" preference val preferenceUpdateCollection = Preference(activity as Context)
// val preferenceUpdateCollection: Preference = Preference(activity as Context) preferenceUpdateCollection.title = getString(R.string.pref_update_collection_title)
// preferenceUpdateCollection.title = getString(R.string.pref_update_collection_title) preferenceUpdateCollection.setIcon(R.drawable.ic_refresh_24dp)
// preferenceUpdateCollection.setIcon(R.drawable.ic_refresh_24dp) preferenceUpdateCollection.summary = getString(R.string.pref_update_collection_summary)
// preferenceUpdateCollection.summary = getString(R.string.pref_update_collection_summary) preferenceUpdateCollection.setOnPreferenceClickListener {
// preferenceUpdateCollection.setOnPreferenceClickListener { // show dialog
// // show dialog YesNoDialog(this).show(
// YesNoDialog(this).show(context = activity as Context, type = Keys.DIALOG_UPDATE_COLLECTION, message = R.string.dialog_yes_no_message_update_collection, yesButton = R.string.dialog_yes_no_positive_button_update_collection) context = activity as Context,
// return@setOnPreferenceClickListener true type = Keys.DIALOG_UPDATE_COLLECTION,
// } message = R.string.dialog_yes_no_message_update_collection,
yesButton = R.string.dialog_yes_no_positive_button_update_collection,
)
return@setOnPreferenceClickListener true
}
// set up "M3U Export" preference // set up "M3U Export" preference
@@ -204,7 +164,8 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
preferenceEnableEditingStreamUri.key = Keys.PREF_EDIT_STREAMS_URIS preferenceEnableEditingStreamUri.key = Keys.PREF_EDIT_STREAMS_URIS
preferenceEnableEditingStreamUri.summaryOn = getString(R.string.pref_edit_station_stream_summary_enabled) preferenceEnableEditingStreamUri.summaryOn = getString(R.string.pref_edit_station_stream_summary_enabled)
preferenceEnableEditingStreamUri.summaryOff = getString(R.string.pref_edit_station_stream_summary_disabled) preferenceEnableEditingStreamUri.summaryOff = getString(R.string.pref_edit_station_stream_summary_disabled)
preferenceEnableEditingStreamUri.setDefaultValue(PreferencesHelper.loadEditStreamUrisEnabled()) preferenceEnableEditingStreamUri.setDefaultValue(PreferencesHelper.loadEditStreamUrisEnabled(context))
preferenceEnableEditingStreamUri.isEnabled = PreferencesHelper.loadEditStreamUrisEnabled(context)
// set up "Edit Stations" preference // set up "Edit Stations" preference
@@ -214,7 +175,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
preferenceEnableEditingGeneral.key = Keys.PREF_EDIT_STATIONS preferenceEnableEditingGeneral.key = Keys.PREF_EDIT_STATIONS
preferenceEnableEditingGeneral.summaryOn = getString(R.string.pref_edit_station_summary_enabled) preferenceEnableEditingGeneral.summaryOn = getString(R.string.pref_edit_station_summary_enabled)
preferenceEnableEditingGeneral.summaryOff = getString(R.string.pref_edit_station_summary_disabled) preferenceEnableEditingGeneral.summaryOff = getString(R.string.pref_edit_station_summary_disabled)
preferenceEnableEditingGeneral.setDefaultValue(PreferencesHelper.loadEditStationsEnabled()) preferenceEnableEditingGeneral.setDefaultValue(PreferencesHelper.loadEditStationsEnabled(context))
preferenceEnableEditingGeneral.setOnPreferenceChangeListener { _, newValue -> preferenceEnableEditingGeneral.setOnPreferenceChangeListener { _, newValue ->
when (newValue) { when (newValue) {
true -> { true -> {
@@ -228,6 +189,75 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
return@setOnPreferenceChangeListener true return@setOnPreferenceChangeListener true
} }
// set up "Bass Boost" preference
val preferenceBassBoost = MarqueeSwitchPreference(context)
preferenceBassBoost.title = getString(R.string.pref_bass_boost_title)
preferenceBassBoost.setIcon(R.drawable.ic_music_note_24dp)
preferenceBassBoost.key = Keys.PREF_BASS_BOOST
preferenceBassBoost.isEnabled = currentPreset.isEmpty()
preferenceBassBoost.summary = getString(R.string.pref_bass_boost_summary)
preferenceBassBoost.setDefaultValue(false)
// set up "Reverb" preference
val preferenceReverb = MarqueeSwitchPreference(context)
preferenceReverb.title = getString(R.string.pref_reverb_title)
preferenceReverb.setIcon(R.drawable.ic_music_note_24dp)
preferenceReverb.key = Keys.PREF_REVERB
preferenceReverb.isEnabled = currentPreset.isEmpty()
preferenceReverb.summary = getString(R.string.pref_reverb_summary)
preferenceReverb.setDefaultValue(false)
// set up "DRC" preference
val preferenceDrc = MarqueeSwitchPreference(context)
preferenceDrc.title = getString(R.string.pref_drc_title)
preferenceDrc.setIcon(R.drawable.ic_music_note_24dp)
preferenceDrc.key = Keys.PREF_DRC
preferenceDrc.isEnabled = currentPreset.isEmpty()
preferenceDrc.summary = getString(R.string.pref_drc_summary)
preferenceDrc.setDefaultValue(true)
// set up "Preset Selection" preference
val preferencePresetSelection = Preference(context)
preferencePresetSelection.title = getString(R.string.pref_preset_selection_title)
preferencePresetSelection.setIcon(R.drawable.ic_music_note_24dp)
preferencePresetSelection.key = Keys.PREF_PRESET_SELECTED
val presetSummary = currentPreset.ifEmpty {
getString(R.string.pref_preset_none)
}
preferencePresetSelection.summary = "${getString(R.string.pref_preset_selection_summary)}: $presetSummary"
preferencePresetSelection.setOnPreferenceClickListener {
PresetSelectionDialog(this).show(activity as Context)
return@setOnPreferenceClickListener true
}
// Initialize EQ control states based on current preset
updateEqControlStates()
// set up "Equalizer" preference entry
val preferenceEqualizer = Preference(context)
preferenceEqualizer.title = getString(R.string.pref_equalizer_title)
preferenceEqualizer.setIcon(R.drawable.ic_music_note_24dp)
preferenceEqualizer.key = Keys.PREF_EQUALIZER
if (currentPreset.isEmpty()) {
preferenceEqualizer.summary = getString(R.string.pref_equalizer_summary)
preferenceEqualizer.isEnabled = true
} else {
preferenceEqualizer.summary = getString(R.string.pref_equalizer_summary_off)
preferenceEqualizer.isEnabled = false
}
preferenceEqualizer.setOnPreferenceClickListener {
findNavController().navigate(R.id.action_settings_to_equalizer)
return@setOnPreferenceClickListener true
}
val preferenceVisualizer = Preference(context)
preferenceVisualizer.title = getString(R.string.pref_visualizer_title)
preferenceVisualizer.setIcon(R.drawable.ic_music_note_24dp)
preferenceVisualizer.summary = getString(R.string.pref_visualizer_summary)
preferenceVisualizer.setOnPreferenceClickListener {
findNavController().navigate(R.id.action_settings_to_visualizer)
return@setOnPreferenceClickListener true
}
// set up "App Version" preference // set up "App Version" preference
val preferenceAppVersion = Preference(context) val preferenceAppVersion = Preference(context)
@@ -239,10 +269,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
val clip: ClipData = ClipData.newPlainText("simple text", preferenceAppVersion.summary) val clip: ClipData = ClipData.newPlainText("simple text", preferenceAppVersion.summary)
val cm: ClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val cm: ClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cm.setPrimaryClip(clip) cm.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
// since API 33 (TIRAMISU) the OS displays its own notification when content is copied to the clipboard
Snackbar.make(requireView(), R.string.toastmessage_copied_to_clipboard, Snackbar.LENGTH_LONG).show() Snackbar.make(requireView(), R.string.toastmessage_copied_to_clipboard, Snackbar.LENGTH_LONG).show()
}
return@setOnPreferenceClickListener true return@setOnPreferenceClickListener true
} }
@@ -281,54 +308,122 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
// set preference categories // set preference categories
val preferenceCategoryGeneral = PreferenceCategory(activity as Context) val preferenceCategoryGeneral = PreferenceCategory(activity as Context)
preferenceCategoryGeneral.title = getString(R.string.pref_general_title) preferenceCategoryGeneral.title = getString(R.string.pref_general_title)
preferenceCategoryGeneral.contains(preferenceThemeSelection)
val preferenceCategoryAudioEffects = PreferenceCategory(context)
preferenceCategoryAudioEffects.title = getString(R.string.pref_audio_effects_title)
val preferenceCategoryMaintenance = PreferenceCategory(activity as Context) val preferenceCategoryMaintenance = PreferenceCategory(activity as Context)
preferenceCategoryMaintenance.title = getString(R.string.pref_maintenance_title) preferenceCategoryMaintenance.title = getString(R.string.pref_maintenance_title)
preferenceCategoryMaintenance.contains(preferenceUpdateStationImages)
// preferenceCategoryMaintenance.contains(preferenceUpdateCollection)
val preferenceCategoryImportExport = PreferenceCategory(activity as Context) val preferenceCategoryImportExport = PreferenceCategory(activity as Context)
preferenceCategoryImportExport.title = getString(R.string.pref_backup_import_export_title) preferenceCategoryImportExport.title = getString(R.string.pref_backup_import_export_title)
preferenceCategoryImportExport.contains(preferenceM3uExport)
preferenceCategoryImportExport.contains(preferencePlsExport)
preferenceCategoryImportExport.contains(preferenceBackupCollection)
preferenceCategoryImportExport.contains(preferenceRestoreCollection)
val preferenceCategoryAdvanced = PreferenceCategory(activity as Context) val preferenceCategoryAdvanced = PreferenceCategory(activity as Context)
preferenceCategoryAdvanced.title = getString(R.string.pref_advanced_title) preferenceCategoryAdvanced.title = getString(R.string.pref_advanced_title)
preferenceCategoryAdvanced.contains(preferenceBufferSize)
preferenceCategoryAdvanced.contains(preferenceEnableEditingGeneral)
preferenceCategoryAdvanced.contains(preferenceEnableEditingStreamUri)
val preferenceCategoryLinks = PreferenceCategory(context) val preferenceCategoryLinks = PreferenceCategory(context)
preferenceCategoryLinks.title = getString(R.string.pref_links_title) preferenceCategoryLinks.title = getString(R.string.pref_links_title)
preferenceCategoryLinks.contains(preferenceAppVersion)
preferenceCategoryLinks.contains(preferenceGitHub)
// setup preference screen // setup preference screen
screen.addPreference(preferenceAppVersion) screen.addPreference(preferenceAppVersion)
screen.addPreference(preferenceLicense)
screen.addPreference(preferenceCategoryGeneral) screen.addPreference(preferenceCategoryGeneral)
screen.addPreference(preferenceThemeSelection) preferenceCategoryGeneral.addPreference(preferenceThemeSelection)
screen.addPreference(preferenceCategoryAudioEffects)
preferenceCategoryAudioEffects.addPreference(preferenceBassBoost)
preferenceCategoryAudioEffects.addPreference(preferenceReverb)
preferenceCategoryAudioEffects.addPreference(preferenceDrc)
preferenceCategoryAudioEffects.addPreference(preferencePresetSelection)
preferenceCategoryAudioEffects.addPreference(preferenceEqualizer)
preferenceCategoryAudioEffects.addPreference(preferenceVisualizer)
screen.addPreference(preferenceCategoryMaintenance) screen.addPreference(preferenceCategoryMaintenance)
screen.addPreference(preferenceUpdateStationImages) preferenceCategoryMaintenance.addPreference(preferenceUpdateStationImages)
// screen.addPreference(preferenceUpdateCollection) preferenceCategoryMaintenance.addPreference(preferenceUpdateCollection)
screen.addPreference(preferenceCategoryImportExport) screen.addPreference(preferenceCategoryImportExport)
screen.addPreference(preferenceM3uExport) preferenceCategoryImportExport.addPreference(preferenceM3uExport)
screen.addPreference(preferencePlsExport) preferenceCategoryImportExport.addPreference(preferencePlsExport)
screen.addPreference(preferenceBackupCollection) preferenceCategoryImportExport.addPreference(preferenceBackupCollection)
screen.addPreference(preferenceRestoreCollection) preferenceCategoryImportExport.addPreference(preferenceRestoreCollection)
screen.addPreference(preferenceCategoryAdvanced) screen.addPreference(preferenceCategoryAdvanced)
screen.addPreference(preferenceBufferSize) preferenceCategoryAdvanced.addPreference(preferenceBufferSize)
screen.addPreference(preferenceEnableEditingGeneral) preferenceCategoryAdvanced.addPreference(preferenceEnableEditingGeneral)
screen.addPreference(preferenceEnableEditingStreamUri) preferenceCategoryAdvanced.addPreference(preferenceEnableEditingStreamUri)
screen.addPreference(preferenceCategoryLinks) screen.addPreference(preferenceCategoryLinks)
screen.addPreference(preferenceGitHub) preferenceCategoryLinks.addPreference(preferenceGitHub)
preferenceCategoryLinks.addPreference(preferenceLicense)
preferenceScreen = screen preferenceScreen = screen
} }
/* Overrides onThemeSelectionDialog from ThemeSelectionDialogListener */
override fun onThemeSelectionDialog(dialogResult: Boolean, selectedTheme: String) {
if (dialogResult) {
// update summary
val themes = arrayOf(
getString(R.string.pref_theme_selection_mode_device_default),
getString(R.string.pref_theme_selection_mode_light),
getString(R.string.pref_theme_selection_mode_dark)
)
val themeValues = arrayOf(
Keys.STATE_THEME_FOLLOW_SYSTEM,
Keys.STATE_THEME_LIGHT_MODE,
Keys.STATE_THEME_DARK_MODE
)
val index = themeValues.indexOf(selectedTheme)
val preferenceThemeSelection = findPreference<Preference>(Keys.PREF_THEME_SELECTION)
preferenceThemeSelection?.summary = "${getString(R.string.pref_theme_selection_summary)} ${themes[index]}"
}
}
/* Overrides onPresetSelectionDialog from PresetSelectionDialogListener */
override fun onPresetSelectionDialog(dialogResult: Boolean, selectedPreset: String) {
if (dialogResult) {
// update summary
val presetPreference = findPreference<Preference>(Keys.PREF_PRESET_SELECTED)
val presetSummary = selectedPreset.ifEmpty {
getString(R.string.pref_preset_none)
}
presetPreference?.summary = "${getString(R.string.pref_preset_selection_summary)}: $presetSummary"
// Enable/disable manual EQ controls based on preset selection
updateEqControlStates()
}
}
/* Updates the enabled/disabled state of EQ controls based on preset selection */
private fun updateEqControlStates() {
val currentPreset = PreferencesHelper.loadSelectedPreset()
val isPresetSelected = currentPreset.isNotEmpty()
// Update Bass Boost
findPreference<Preference>(Keys.PREF_BASS_BOOST)?.isEnabled = !isPresetSelected
// Update Reverb
findPreference<Preference>(Keys.PREF_REVERB)?.isEnabled = !isPresetSelected
// Update DRC
findPreference<Preference>(Keys.PREF_DRC)?.isEnabled = !isPresetSelected
// Update Equalizer with proper key
val preferenceEqualizer = findPreference<Preference>(Keys.PREF_EQUALIZER)
if (preferenceEqualizer != null) {
if (isPresetSelected) {
preferenceEqualizer.summary = getString(R.string.pref_equalizer_summary_off)
preferenceEqualizer.isEnabled = false
} else {
preferenceEqualizer.summary = getString(R.string.pref_equalizer_summary)
preferenceEqualizer.isEnabled = true
}
}
}
/* Overrides onYesNoDialog from YesNoDialogListener */ /* Overrides onYesNoDialog from YesNoDialogListener */
override fun onYesNoDialog( override fun onYesNoDialog(
@@ -437,9 +532,9 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
val sourceUri: Uri? = result.data?.data val sourceUri: Uri? = result.data?.data
if (sourceUri != null) { if (sourceUri != null) {
// open and import OPML in player fragment // open and import OPML in player fragment
val bundle: Bundle = bundleOf( val bundle = Bundle().apply {
Keys.ARG_RESTORE_COLLECTION to "$sourceUri" putString(Keys.ARG_RESTORE_COLLECTION, "$sourceUri")
) }
this.findNavController().navigate(R.id.player_destination, bundle) this.findNavController().navigate(R.id.player_destination, bundle)
} }
} }
@@ -455,7 +550,9 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
Snackbar.LENGTH_LONG Snackbar.LENGTH_LONG
).show() ).show()
// update collection in player screen // update collection in player screen
val bundle: Bundle = bundleOf(Keys.ARG_UPDATE_COLLECTION to true) val bundle = Bundle().apply {
putBoolean(Keys.ARG_UPDATE_COLLECTION, true)
}
this.findNavController().navigate(R.id.player_destination, bundle) this.findNavController().navigate(R.id.player_destination, bundle)
} else { } else {
ErrorDialog().show( ErrorDialog().show(
@@ -476,9 +573,9 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
Snackbar.LENGTH_LONG Snackbar.LENGTH_LONG
).show() ).show()
// update collection in player screen // update collection in player screen
val bundle: Bundle = bundleOf( val bundle = Bundle().apply {
Keys.ARG_UPDATE_IMAGES to true putBoolean(Keys.ARG_UPDATE_IMAGES, true)
) }
this.findNavController().navigate(R.id.player_destination, bundle) this.findNavController().navigate(R.id.player_destination, bundle)
} else { } else {
ErrorDialog().show( ErrorDialog().show(
@@ -512,28 +609,6 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
} }
/* Opens up a file picker to select the save location */
private fun openSavePlsDialog() {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = Keys.MIME_TYPE_PLS
val timeStamp: String
val dateFormat = SimpleDateFormat("_yyyy-MM-dd'T'HH_mm", Locale.US)
timeStamp = dateFormat.format(Date())
putExtra(Intent.EXTRA_TITLE, "collection$timeStamp.pls")
}
// file gets saved in the ActivityResult
try {
requestSavePlsLauncher.launch(intent)
} catch (exception: Exception) {
Log.e(TAG, "Unable to save PLS.\n$exception")
Snackbar.make(requireView(), R.string.toastmessage_install_file_helper, Snackbar.LENGTH_LONG).show()
}
}
/* Opens up a file picker to select the backup location */ /* Opens up a file picker to select the backup location */
private fun openBackupCollectionDialog() { private fun openBackupCollectionDialog() {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
@@ -568,7 +643,26 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
requestRestoreCollectionLauncher.launch(intent) requestRestoreCollectionLauncher.launch(intent)
} catch (exception: Exception) { } catch (exception: Exception) {
Log.e(TAG, "Unable to open file picker for ZIP.\n$exception") Log.e(TAG, "Unable to open file picker for ZIP.\n$exception")
// Toast.makeText(activity as Context, R.string.toast_message_install_file_helper, Toast.LENGTH_LONG).show() }
}
private fun openSavePlsDialog() {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = Keys.MIME_TYPE_PLS
val timeStamp: String
val dateFormat = SimpleDateFormat("_yyyy-MM-dd'T'HH_mm", Locale.US)
timeStamp = dateFormat.format(Date())
putExtra(Intent.EXTRA_TITLE, "collection$timeStamp.pls")
}
// file gets saved in the ActivityResult
try {
requestSavePlsLauncher.launch(intent)
} catch (exception: Exception) {
Log.e(TAG, "Unable to save PLS.\n$exception")
Snackbar.make(requireView(), R.string.toastmessage_install_file_helper, Snackbar.LENGTH_LONG).show()
} }
} }
} }
@@ -0,0 +1,122 @@
package com.michatec.radio
import android.content.ComponentName
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import androidx.preference.PreferenceFragmentCompat
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import com.michatec.radio.extensions.requestVisualizerData
import com.michatec.radio.helpers.ExtrasHelper
/*
* VisualizerFragment class: Handles audio visualization
*/
@OptIn(UnstableApi::class)
class VisualizerFragment : PreferenceFragmentCompat() {
private val TAG = "VisualizerFragment"
private lateinit var controllerFuture: ListenableFuture<MediaController>
private val controller: MediaController?
get() = if (this::controllerFuture.isInitialized && controllerFuture.isDone) {
try { controllerFuture.get() } catch (_: Exception) { null }
} else null
private var visualizerPref: ExtrasHelper.VisualizerPreference? = null
private val handler = Handler(Looper.getMainLooper())
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.pref_visualizer_title)
(activity as AppCompatActivity).supportActionBar?.show()
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
val context = preferenceManager.context
val screen = preferenceManager.createPreferenceScreen(context)
visualizerPref = ExtrasHelper.VisualizerPreference(context)
visualizerPref?.key = "visualizer_key"
screen.addPreference(visualizerPref!!)
preferenceScreen = screen
}
override fun onStart() {
super.onStart()
initializeController()
}
override fun onStop() {
super.onStop()
releaseController()
}
override fun onResume() {
super.onResume()
startPolling()
}
override fun onPause() {
super.onPause()
stopPolling()
}
private fun initializeController() {
controllerFuture = MediaController.Builder(
requireContext(),
SessionToken(requireContext(), ComponentName(requireContext(), PlayerService::class.java))
).buildAsync()
controllerFuture.addListener({
Log.d(TAG, "MediaController connected: ${controller != null}")
}, MoreExecutors.directExecutor())
}
private fun releaseController() {
if (this::controllerFuture.isInitialized) {
MediaController.releaseFuture(controllerFuture)
}
}
private val pollRunnable = object : Runnable {
override fun run() {
val c = controller
if (c != null && c.isPlaying) {
val resultFuture = c.requestVisualizerData()
resultFuture.addListener({
try {
val result = resultFuture.get()
if (result.resultCode == androidx.media3.session.SessionResult.RESULT_SUCCESS) {
val data = result.extras.getFloatArray(Keys.EXTRA_VISUALIZER_DATA)
if (data != null && data.isNotEmpty()) {
visualizerPref?.update(data)
}
} else {
Log.e(TAG, "Custom command failed with result code: ${result.resultCode}")
}
} catch (e: Exception) {
Log.e(TAG, "Error fetching visualizer data", e)
}
}, MoreExecutors.directExecutor())
}
handler.postDelayed(this, 18) // ~60 FPS
}
}
private fun startPolling() {
handler.removeCallbacks(pollRunnable)
handler.post(pollRunnable)
}
private fun stopPolling() {
handler.removeCallbacks(pollRunnable)
}
}
@@ -1,33 +1,22 @@
/*
* CollectionAdapter.kt
* Implements the CollectionAdapter class
* A CollectionAdapter is a custom adapter providing station card views for a RecyclerView
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.collection package com.michatec.radio.collection
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.res.ColorStateList
import android.text.Editable import android.text.Editable
import android.text.TextWatcher import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.widget.ImageView import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.Group import androidx.constraintlayout.widget.Group
import androidx.core.content.ContextCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.core.view.isVisible import androidx.core.view.isVisible
@@ -37,6 +26,7 @@ import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
import com.michatec.radio.Keys import com.michatec.radio.Keys
@@ -61,11 +51,12 @@ class CollectionAdapter(
/* Main class variables */ /* Main class variables */
private lateinit var collectionViewModel: CollectionViewModel private lateinit var collectionViewModel: CollectionViewModel
private var collection: Collection = Collection() private var collection: Collection = Collection()
private var editStationsEnabled: Boolean = PreferencesHelper.loadEditStationsEnabled() private var editStationsEnabled: Boolean = PreferencesHelper.loadEditStationsEnabled(context)
private var editStationStreamsEnabled: Boolean = PreferencesHelper.loadEditStreamUrisEnabled() private var editStationStreamsEnabled: Boolean = PreferencesHelper.loadEditStreamUrisEnabled(context)
private var expandedStationUuid: String = PreferencesHelper.loadStationListStreamUuid() private var expandedStationUuid: String = PreferencesHelper.loadStationListStreamUuid()
private var expandedStationPosition: Int = -1 private var expandedStationPosition: Int = -1
var isExpandedForEdit: Boolean = false var isExpandedForEdit: Boolean = false
private var reorderStationUuid: String = ""
/* Listener Interface */ /* Listener Interface */
@@ -178,6 +169,9 @@ class CollectionAdapter(
addNewViewHolder.settingsButtonView.setOnClickListener { addNewViewHolder.settingsButtonView.setOnClickListener {
it.findNavController().navigate(R.id.settings_destination) it.findNavController().navigate(R.id.settings_destination)
} }
addNewViewHolder.visualizerButtonView.setOnClickListener {
it.findNavController().navigate(R.id.visualizer_destination)
}
} }
// CASE STATION CARD // CASE STATION CARD
is StationViewHolder -> { is StationViewHolder -> {
@@ -193,6 +187,19 @@ class CollectionAdapter(
setStationImage(stationViewHolder, station) setStationImage(stationViewHolder, station)
setStationButtons(stationViewHolder, station) setStationButtons(stationViewHolder, station)
setEditViews(stationViewHolder, station) setEditViews(stationViewHolder, station)
setPlaybackProgress(stationViewHolder, station)
setDownloadProgress(stationViewHolder, station)
stationViewHolder.playButtonView.isGone = true
// highlight if reordering
if (reorderStationUuid == station.uuid) {
stationViewHolder.stationCardView.setStrokeColor(
ColorStateList.valueOf(
ContextCompat.getColor(context, R.color.cardview_reordering)
)
)
}
// show / hide edit views // show / hide edit views
when (expandedStationPosition) { when (expandedStationPosition) {
@@ -211,6 +218,8 @@ class CollectionAdapter(
stationViewHolder.stationNameEditView.imeOptions = stationViewHolder.stationNameEditView.imeOptions =
EditorInfo.IME_ACTION_DONE EditorInfo.IME_ACTION_DONE
} }
// Allow internal focus
stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
} }
// hide edit views // hide edit views
else -> { else -> {
@@ -219,6 +228,8 @@ class CollectionAdapter(
stationViewHolder.stationStarredView.isVisible = station.starred stationViewHolder.stationStarredView.isVisible = station.starred
stationViewHolder.editViews.isGone = true stationViewHolder.editViews.isGone = true
stationViewHolder.stationUriEditView.isGone = true stationViewHolder.stationUriEditView.isGone = true
// Block internal focus
stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
} }
} }
} }
@@ -248,6 +259,28 @@ class CollectionAdapter(
} }
/* Sets the playback progress view */
private fun setPlaybackProgress(stationViewHolder: StationViewHolder, station: Station) {
if (station.bufferingProgress > 0) {
stationViewHolder.bufferingProgress.progress = station.bufferingProgress
stationViewHolder.bufferingProgress.isVisible = true
} else {
stationViewHolder.bufferingProgress.isGone = true
}
}
/* Sets the download progress view */
private fun setDownloadProgress(stationViewHolder: StationViewHolder, station: Station) {
if (station.downloadProgress > 0) {
stationViewHolder.downloadProgress.progress = station.downloadProgress
stationViewHolder.downloadProgress.isVisible = true
} else {
stationViewHolder.downloadProgress.isGone = true
}
}
/* Sets the edit views */ /* Sets the edit views */
private fun setEditViews(stationViewHolder: StationViewHolder, station: Station) { private fun setEditViews(stationViewHolder: StationViewHolder, station: Station) {
stationViewHolder.stationNameEditView.setText(station.name, TextView.BufferType.EDITABLE) stationViewHolder.stationNameEditView.setText(station.name, TextView.BufferType.EDITABLE)
@@ -264,12 +297,12 @@ class CollectionAdapter(
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}) })
stationViewHolder.cancelButton.setOnClickListener { stationViewHolder.cancelButton.setOnClickListener {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView)
} }
stationViewHolder.saveButton.setOnClickListener { stationViewHolder.saveButton.setOnClickListener {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
saveStation( saveStation(
station, station,
@@ -280,22 +313,38 @@ class CollectionAdapter(
UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView)
} }
stationViewHolder.placeOnHomeScreenButton.setOnClickListener { stationViewHolder.placeOnHomeScreenButton.setOnClickListener {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
ShortcutHelper.placeShortcut(context, station) ShortcutHelper.placeShortcut(context, station)
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView)
} }
stationViewHolder.stationImageChangeView.setOnClickListener { stationViewHolder.stationImageChangeView.setOnClickListener {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
collectionAdapterListener.onChangeImageButtonTapped(station.uuid) collectionAdapterListener.onChangeImageButtonTapped(station.uuid)
stationViewHolder.adapterPosition stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView)
} }
} }
/* Shows / hides the reorder highlight for a station */
private fun toggleReorderMode(position: Int, stationUuid: String) {
if (reorderStationUuid == stationUuid) {
reorderStationUuid = ""
saveCollectionAfterDragDrop()
} else {
// collapse edit views if necessary
if (isExpandedForEdit) {
toggleEditViews(expandedStationPosition, expandedStationUuid)
}
reorderStationUuid = stationUuid
}
notifyItemChanged(position)
}
/* Shows / hides the edit view for a station */ /* Shows / hides the edit view for a station */
@SuppressLint("NotifyDataSetChanged")
private fun toggleEditViews(position: Int, stationUuid: String) { private fun toggleEditViews(position: Int, stationUuid: String) {
when (stationUuid) { when (stationUuid) {
// CASE: this station's edit view is already expanded // CASE: this station's edit view is already expanded
@@ -328,12 +377,16 @@ class CollectionAdapter(
when (station.starred) { when (station.starred) {
true -> { true -> {
if (station.imageColor != -1) { if (station.imageColor != -1) {
// stationViewHolder.stationCardView.setCardBackgroundColor(station.imageColor)
stationViewHolder.stationStarredView.setColorFilter(station.imageColor) stationViewHolder.stationStarredView.setColorFilter(station.imageColor)
} else {
stationViewHolder.stationStarredView.clearColorFilter()
} }
stationViewHolder.stationStarredView.isVisible = true stationViewHolder.stationStarredView.isVisible = true
} }
false -> stationViewHolder.stationStarredView.isGone = true false -> {
stationViewHolder.stationStarredView.clearColorFilter()
stationViewHolder.stationStarredView.isGone = true
}
} }
} }
@@ -361,6 +414,8 @@ class CollectionAdapter(
false -> stationViewHolder.playButtonView.visibility = View.INVISIBLE false -> stationViewHolder.playButtonView.visibility = View.INVISIBLE
} }
stationViewHolder.stationCardView.setOnClickListener { stationViewHolder.stationCardView.setOnClickListener {
if (reorderStationUuid.isNotEmpty()) return@setOnClickListener
if (expandedStationPosition == stationViewHolder.bindingAdapterPosition) return@setOnClickListener
collectionAdapterListener.onPlayButtonTapped(station.uuid) collectionAdapterListener.onPlayButtonTapped(station.uuid)
} }
stationViewHolder.playButtonView.setOnClickListener { stationViewHolder.playButtonView.setOnClickListener {
@@ -375,9 +430,71 @@ class CollectionAdapter(
stationViewHolder.stationImageView.setOnClickListener { stationViewHolder.stationImageView.setOnClickListener {
collectionAdapterListener.onPlayButtonTapped(station.uuid) collectionAdapterListener.onPlayButtonTapped(station.uuid)
} }
// TV improvement: Allow reordering with DPAD
stationViewHolder.stationCardView.setOnKeyListener { _, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN) {
// Reorder mode handling
if (reorderStationUuid == station.uuid) {
when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> {
val currentPos = stationViewHolder.bindingAdapterPosition
if (currentPos > 0) {
onItemMove(currentPos, currentPos - 1)
}
return@setOnKeyListener true
}
KeyEvent.KEYCODE_DPAD_DOWN -> {
val currentPos = stationViewHolder.bindingAdapterPosition
if (currentPos < collection.stations.size - 1) {
onItemMove(currentPos, currentPos + 1)
}
return@setOnKeyListener true
}
KeyEvent.KEYCODE_NUMPAD_2, KeyEvent.KEYCODE_2, KeyEvent.KEYCODE_PLUS,
KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_DPAD_CENTER -> {
toggleReorderMode(stationViewHolder.bindingAdapterPosition, station.uuid)
return@setOnKeyListener true
}
else -> return@setOnKeyListener true // Consume other keys in reorder mode
}
}
when (keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> {
if (editStationsEnabled && expandedStationPosition != stationViewHolder.bindingAdapterPosition) {
val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid)
return@setOnKeyListener true
}
}
KeyEvent.KEYCODE_NUMPAD_3, KeyEvent.KEYCODE_3, KeyEvent.KEYCODE_BACK -> {
if (expandedStationPosition == stationViewHolder.bindingAdapterPosition) {
val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid)
return@setOnKeyListener true
}
}
KeyEvent.KEYCODE_NUMPAD_0, KeyEvent.KEYCODE_0, KeyEvent.KEYCODE_DEL -> {
removeStation(context, stationViewHolder.bindingAdapterPosition)
return@setOnKeyListener true
}
KeyEvent.KEYCODE_NUMPAD_1, KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_SPACE -> {
toggleStarredStation(context, stationViewHolder.bindingAdapterPosition)
return@setOnKeyListener true
}
KeyEvent.KEYCODE_NUMPAD_2, KeyEvent.KEYCODE_2, KeyEvent.KEYCODE_PLUS -> {
toggleReorderMode(stationViewHolder.bindingAdapterPosition, station.uuid)
return@setOnKeyListener true
}
}
}
false
}
stationViewHolder.playButtonView.setOnLongClickListener { stationViewHolder.playButtonView.setOnLongClickListener {
if (editStationsEnabled) { if (editStationsEnabled) {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
return@setOnLongClickListener true return@setOnLongClickListener true
} else { } else {
@@ -386,7 +503,7 @@ class CollectionAdapter(
} }
stationViewHolder.stationNameView.setOnLongClickListener { stationViewHolder.stationNameView.setOnLongClickListener {
if (editStationsEnabled) { if (editStationsEnabled) {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
return@setOnLongClickListener true return@setOnLongClickListener true
} else { } else {
@@ -395,7 +512,7 @@ class CollectionAdapter(
} }
stationViewHolder.stationStarredView.setOnLongClickListener { stationViewHolder.stationStarredView.setOnLongClickListener {
if (editStationsEnabled) { if (editStationsEnabled) {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
return@setOnLongClickListener true return@setOnLongClickListener true
} else { } else {
@@ -404,7 +521,7 @@ class CollectionAdapter(
} }
stationViewHolder.stationImageView.setOnLongClickListener { stationViewHolder.stationImageView.setOnLongClickListener {
if (editStationsEnabled) { if (editStationsEnabled) {
val position: Int = stationViewHolder.adapterPosition val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid) toggleEditViews(position, station.uuid)
return@setOnLongClickListener true return@setOnLongClickListener true
} else { } else {
@@ -470,24 +587,25 @@ class CollectionAdapter(
} else if (holder is StationViewHolder) { } else if (holder is StationViewHolder) {
// get station from position // get station from position
collection.stations[holder.getAdapterPosition()] val station: Station = collection.stations[holder.bindingAdapterPosition]
for (data in payloads) { for (data in payloads) {
when (data as Int) { when (data as Int) {
Keys.HOLDER_UPDATE_COVER -> { Keys.HOLDER_UPDATE_COVER -> {
// todo implement setStationImage(holder, station)
setStarredIcon(holder, station)
} }
Keys.HOLDER_UPDATE_NAME -> { Keys.HOLDER_UPDATE_NAME -> {
// todo implement setStationName(holder, station)
} }
Keys.HOLDER_UPDATE_PLAYBACK_STATE -> { Keys.HOLDER_UPDATE_PLAYBACK_STATE -> {
// todo implement setStationButtons(holder, station)
} }
Keys.HOLDER_UPDATE_PLAYBACK_PROGRESS -> { Keys.HOLDER_UPDATE_PLAYBACK_PROGRESS -> {
// todo implement setPlaybackProgress(holder, station)
} }
Keys.HOLDER_UPDATE_DOWNLOAD_STATE -> { Keys.HOLDER_UPDATE_DOWNLOAD_STATE -> {
// todo implement setDownloadProgress(holder, station)
} }
} }
} }
@@ -574,21 +692,6 @@ class CollectionAdapter(
} }
// /* Initiates update of a station's information */ // todo move to CollectionHelper
// private fun updateStation(context: Context, station: Station) {
// if (station.radioBrowserStationUuid.isNotEmpty()) {
// // get updated station from radio browser - results are handled by onRadioBrowserSearchResults
// val radioBrowserSearch: RadioBrowserSearch = RadioBrowserSearch(context, this)
// radioBrowserSearch.searchStation(context, station.radioBrowserStationUuid, Keys.SEARCH_TYPE_BY_UUID)
// } else if (station.remoteStationLocation.isNotEmpty()) {
// // download playlist // todo check content type detection is necessary here
// DownloadHelper.downloadPlaylists(context, arrayOf(station.remoteStationLocation))
// } else {
// Log.w(TAG, "Unable to update station: ${station.name}.")
// }
// }
/* Determines if position is last */ /* Determines if position is last */
private fun isPositionFooter(position: Int): Boolean { private fun isPositionFooter(position: Int): Boolean {
return position == collection.stations.size return position == collection.stations.size
@@ -599,7 +702,7 @@ class CollectionAdapter(
@SuppressLint("NotifyDataSetChanged") @SuppressLint("NotifyDataSetChanged")
private fun updateRecyclerView(oldCollection: Collection, newCollection: Collection) { private fun updateRecyclerView(oldCollection: Collection, newCollection: Collection) {
collection = newCollection collection = newCollection
if (oldCollection.stations.size == 0 && newCollection.stations.size > 0) { if (oldCollection.stations.isEmpty() && newCollection.stations.isNotEmpty()) {
// data set has been initialized - redraw the whole list // data set has been initialized - redraw the whole list
notifyDataSetChanged() notifyDataSetChanged()
} else { } else {
@@ -637,9 +740,9 @@ class CollectionAdapter(
SharedPreferences.OnSharedPreferenceChangeListener { _, key -> SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) { when (key) {
Keys.PREF_EDIT_STATIONS -> editStationsEnabled = Keys.PREF_EDIT_STATIONS -> editStationsEnabled =
PreferencesHelper.loadEditStationsEnabled() PreferencesHelper.loadEditStationsEnabled(context)
Keys.PREF_EDIT_STREAMS_URIS -> editStationStreamsEnabled = Keys.PREF_EDIT_STREAMS_URIS -> editStationStreamsEnabled =
PreferencesHelper.loadEditStreamUrisEnabled() PreferencesHelper.loadEditStreamUrisEnabled(context)
} }
} }
/* /*
@@ -650,12 +753,14 @@ class CollectionAdapter(
/* /*
* Inner class: ViewHolder for the Add New Station action * Inner class: ViewHolder for the Add New Station action
*/ */
private inner class AddNewViewHolder(listItemAddNewLayout: View) : private class AddNewViewHolder(listItemAddNewLayout: View) :
RecyclerView.ViewHolder(listItemAddNewLayout) { RecyclerView.ViewHolder(listItemAddNewLayout) {
val addNewStationView: ExtendedFloatingActionButton = val addNewStationView: ExtendedFloatingActionButton =
listItemAddNewLayout.findViewById(R.id.card_add_new_station) listItemAddNewLayout.findViewById(R.id.card_add_new_station)
val settingsButtonView: ExtendedFloatingActionButton = val settingsButtonView: ExtendedFloatingActionButton =
listItemAddNewLayout.findViewById(R.id.card_settings) listItemAddNewLayout.findViewById(R.id.card_settings)
val visualizerButtonView: ExtendedFloatingActionButton =
listItemAddNewLayout.findViewById(R.id.card_visualizer)
} }
/* /*
* End of inner class * End of inner class
@@ -665,14 +770,15 @@ class CollectionAdapter(
/* /*
* Inner class: ViewHolder for a station * Inner class: ViewHolder for a station
*/ */
private inner class StationViewHolder(stationCardLayout: View) : private class StationViewHolder(stationCardLayout: View) :
RecyclerView.ViewHolder(stationCardLayout) { RecyclerView.ViewHolder(stationCardLayout) {
val stationCardView: CardView = stationCardLayout.findViewById(R.id.station_card) val stationCardView: MaterialCardView = stationCardLayout.findViewById(R.id.station_card)
val stationImageView: ImageView = stationCardLayout.findViewById(R.id.station_icon) val stationImageView: ImageView = stationCardLayout.findViewById(R.id.station_icon)
val stationNameView: TextView = stationCardLayout.findViewById(R.id.station_name) val stationNameView: TextView = stationCardLayout.findViewById(R.id.station_name)
val stationStarredView: ImageView = stationCardLayout.findViewById(R.id.starred_icon) val stationStarredView: ImageView = stationCardLayout.findViewById(R.id.starred_icon)
val bufferingProgress: ProgressBar = stationCardLayout.findViewById(R.id.buffering_progress)
val downloadProgress: ProgressBar = stationCardLayout.findViewById(R.id.download_progress)
// val menuButtonView: ImageView = stationCardLayout.findViewById(R.id.menu_button)
val playButtonView: ImageView = stationCardLayout.findViewById(R.id.playback_button) val playButtonView: ImageView = stationCardLayout.findViewById(R.id.playback_button)
val editViews: Group = stationCardLayout.findViewById(R.id.default_edit_views) val editViews: Group = stationCardLayout.findViewById(R.id.default_edit_views)
val stationImageChangeView: ImageView = val stationImageChangeView: ImageView =
@@ -1,17 +1,3 @@
/*
* CollectionViewModel.kt
* Implements the CollectionViewModel class
* A CollectionViewModel stores the collection of stations as live data
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.collection package com.michatec.radio.collection
import android.app.Application import android.app.Application
@@ -1,16 +1,3 @@
/*
* Collection.kt
* Implements the Collection class
* A Collection object holds a list of radio stations
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.core package com.michatec.radio.core
import android.os.Parcelable import android.os.Parcelable
@@ -1,17 +1,3 @@
/*
* Station.kt
* Implements the Station class
* A Station object holds the base data of a radio
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.core package com.michatec.radio.core
import android.os.Parcelable import android.os.Parcelable
@@ -48,7 +34,9 @@ data class Station(
@Expose var radioBrowserStationUuid: String = String(), @Expose var radioBrowserStationUuid: String = String(),
@Expose var radioBrowserChangeUuid: String = String(), @Expose var radioBrowserChangeUuid: String = String(),
@Expose var bitrate: Int = 0, @Expose var bitrate: Int = 0,
@Expose var codec: String = String() @Expose var codec: String = String(),
@Expose var bufferingProgress: Int = 0,
@Expose var downloadProgress: Int = 0
) : Parcelable { ) : Parcelable {
@@ -79,6 +67,12 @@ data class Station(
} }
/* Getter for media type */
fun getMediaType(): String {
return streamContent
}
/* Creates a deep copy of a Station */ /* Creates a deep copy of a Station */
fun deepCopy(): Station { fun deepCopy(): Station {
return Station( return Station(
@@ -101,7 +95,9 @@ data class Station(
radioBrowserStationUuid = radioBrowserStationUuid, radioBrowserStationUuid = radioBrowserStationUuid,
radioBrowserChangeUuid = radioBrowserChangeUuid, radioBrowserChangeUuid = radioBrowserChangeUuid,
bitrate = bitrate, bitrate = bitrate,
codec = codec codec = codec,
bufferingProgress = bufferingProgress,
downloadProgress = downloadProgress
) )
} }
} }
@@ -1,22 +1,10 @@
/*
* AddStationDialog.kt
* Implements the AddStationDialog class
* A AddStationDialog shows a dialog with list of stations to import
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-23 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.dialogs package com.michatec.radio.dialogs
import android.content.Context import android.content.Context
import android.view.LayoutInflater import android.view.LayoutInflater
import android.widget.Button
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@@ -42,13 +30,11 @@ class AddStationDialog (
} }
/* Define log tag */
private val TAG = AddStationDialog::class.java.simpleName
/* Main class variables */ /* Main class variables */
private lateinit var dialog: AlertDialog private lateinit var dialog: AlertDialog
private lateinit var stationSearchResultList: RecyclerView private lateinit var stationSearchResultList: RecyclerView
private var customPositiveButton: Button? = null
private var customNegativeButton: Button? = null
private lateinit var searchResultAdapter: SearchResultAdapter private lateinit var searchResultAdapter: SearchResultAdapter
private var station: Station = Station() private var station: Station = Station()
@@ -77,6 +63,10 @@ class AddStationDialog (
// set up list of search results // set up list of search results
setupRecyclerView(context) setupRecyclerView(context)
// find custom buttons (for TV layout)
customPositiveButton = view.findViewById(R.id.dialog_positive_button)
customNegativeButton = view.findViewById(R.id.dialog_negative_button)
// add okay ("Add") button // add okay ("Add") button
builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ -> builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ ->
// listen for click on add button // listen for click on add button
@@ -92,6 +82,17 @@ class AddStationDialog (
searchResultAdapter.stopPrePlayback() searchResultAdapter.stopPrePlayback()
} }
// set up custom buttons if they exist (TV layout)
customPositiveButton?.setOnClickListener {
listener.onAddStationDialog(station)
searchResultAdapter.stopPrePlayback()
dialog.dismiss()
}
customNegativeButton?.setOnClickListener {
searchResultAdapter.stopPrePlayback()
dialog.dismiss()
}
// set dialog view // set dialog view
builder.setView(view) builder.setView(view)
@@ -99,9 +100,17 @@ class AddStationDialog (
dialog = builder.create() dialog = builder.create()
dialog.show() dialog.show()
// initially disable "Add" button // handle button visibility and state
if (customPositiveButton != null) {
// hide default buttons if custom ones are used
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isGone = true
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isGone = true
customPositiveButton?.isEnabled = false
} else {
// initially disable default "Add" button
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
} }
}
/* Sets up list of results (RecyclerView) */ /* Sets up list of results (RecyclerView) */
@@ -121,12 +130,14 @@ class AddStationDialog (
/* Implement activateAddButton to enable the "Add" button */ /* Implement activateAddButton to enable the "Add" button */
override fun activateAddButton() { override fun activateAddButton() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true
customPositiveButton?.isEnabled = true
} }
/* Implement deactivateAddButton to disable the "Add" button */ /* Implement deactivateAddButton to disable the "Add" button */
override fun deactivateAddButton() { override fun deactivateAddButton() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
customPositiveButton?.isEnabled = false
} }
@@ -1,17 +1,3 @@
/*
* ErrorDialog.kt
* Implements the ErrorDialog class
* An ErrorDialog shows an error dialog with details
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.dialogs package com.michatec.radio.dialogs
import android.content.Context import android.content.Context
@@ -19,6 +5,7 @@ import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.widget.TextView import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.core.view.isVisible import androidx.core.view.isVisible
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
@@ -46,9 +33,9 @@ class ErrorDialog {
// get views // get views
val inflater: LayoutInflater = LayoutInflater.from(context) val inflater: LayoutInflater = LayoutInflater.from(context)
val view: View = inflater.inflate(R.layout.dialog_generic_with_details, null) val view: View = inflater.inflate(R.layout.dialog_generic_with_details, null)
val errorMessageView: TextView = view.findViewById(R.id.dialog_message) as TextView val errorMessageView: TextView = view.findViewById(R.id.dialog_message)
val errorDetailsLinkView: TextView = view.findViewById(R.id.dialog_details_link) as TextView val errorDetailsLinkView: TextView = view.findViewById(R.id.dialog_details_link)
val errorDetailsView: TextView = view.findViewById(R.id.dialog_details) as TextView val errorDetailsView: TextView = view.findViewById(R.id.dialog_details)
// set dialog view // set dialog view
builder.setView(view) builder.setView(view)
@@ -81,8 +68,7 @@ class ErrorDialog {
// add okay button // add okay button
builder.setPositiveButton(R.string.dialog_generic_button_okay) { _, _ -> builder.setPositiveButton(R.string.dialog_generic_button_okay) { _, _ ->
// listen for click on okay button Toast.makeText(context, R.string.dialog_generic_button_okay, Toast.LENGTH_SHORT).show()
// do nothing
} }
// display error dialog // display error dialog
@@ -1,17 +1,3 @@
/*
* FindStationDialog.kt
* Implements the FindStationDialog class
* A FindStationDialog shows a dialog with search box and list of results
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.dialogs package com.michatec.radio.dialogs
import android.annotation.SuppressLint import android.annotation.SuppressLint
@@ -21,6 +7,7 @@ import android.os.Handler
import android.os.Looper import android.os.Looper
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.ProgressBar import android.widget.ProgressBar
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
@@ -63,6 +50,8 @@ class FindStationDialog (
private lateinit var searchRequestProgressIndicator: ProgressBar private lateinit var searchRequestProgressIndicator: ProgressBar
private lateinit var noSearchResultsTextView: MaterialTextView private lateinit var noSearchResultsTextView: MaterialTextView
private lateinit var stationSearchResultList: RecyclerView private lateinit var stationSearchResultList: RecyclerView
private var customPositiveButton: Button? = null
private var customNegativeButton: Button? = null
private lateinit var searchResultAdapter: SearchResultAdapter private lateinit var searchResultAdapter: SearchResultAdapter
private lateinit var radioBrowserSearch: RadioBrowserSearch private lateinit var radioBrowserSearch: RadioBrowserSearch
private lateinit var directInputCheck: DirectInputCheck private lateinit var directInputCheck: DirectInputCheck
@@ -134,6 +123,10 @@ class FindStationDialog (
// set up list of search results // set up list of search results
setupRecyclerView(context) setupRecyclerView(context)
// find custom buttons (for TV layout)
customPositiveButton = view.findViewById(R.id.dialog_positive_button)
customNegativeButton = view.findViewById(R.id.dialog_negative_button)
// add okay ("Add") button // add okay ("Add") button
builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ -> builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ ->
// listen for click on add button // listen for click on add button
@@ -152,6 +145,18 @@ class FindStationDialog (
searchResultAdapter.stopPrePlayback() searchResultAdapter.stopPrePlayback()
} }
// set up custom buttons if they exist (TV layout)
customPositiveButton?.setOnClickListener {
listener.onFindStationDialog(station)
searchResultAdapter.stopPrePlayback()
dialog.dismiss()
}
customNegativeButton?.setOnClickListener {
radioBrowserSearch.stopSearchRequest()
searchResultAdapter.stopPrePlayback()
dialog.dismiss()
}
// listen for input // listen for input
stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(query: String): Boolean { override fun onQueryTextChange(query: String): Boolean {
@@ -174,11 +179,19 @@ class FindStationDialog (
dialog = builder.create() dialog = builder.create()
dialog.show() dialog.show()
// initially disable "Add" button // handle button visibility and state
if (customPositiveButton != null) {
// hide default buttons if custom ones are used
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isGone = true
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isGone = true
customPositiveButton?.isEnabled = false
} else {
// initially disable default "Add" button
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isAllCaps = true dialog.getButton(AlertDialog.BUTTON_POSITIVE).isAllCaps = true
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isAllCaps = true dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isAllCaps = true
} }
}
/* Sets up list of results (RecyclerView) */ /* Sets up list of results (RecyclerView) */
@@ -242,12 +255,14 @@ class FindStationDialog (
/* Makes the "Add" button clickable */ /* Makes the "Add" button clickable */
override fun activateAddButton() { override fun activateAddButton() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true
customPositiveButton?.isEnabled = true
searchRequestProgressIndicator.isGone = true searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isGone = true noSearchResultsTextView.isGone = true
} }
override fun deactivateAddButton() { override fun deactivateAddButton() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
customPositiveButton?.isEnabled = false
searchRequestProgressIndicator.isGone = true searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isGone = true noSearchResultsTextView.isGone = true
} }
@@ -256,6 +271,7 @@ class FindStationDialog (
/* Resets the dialog layout to default state */ /* Resets the dialog layout to default state */
private fun resetLayout(clearAdapter: Boolean = false) { private fun resetLayout(clearAdapter: Boolean = false) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
customPositiveButton?.isEnabled = false
searchRequestProgressIndicator.isGone = true searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isGone = true noSearchResultsTextView.isGone = true
searchResultAdapter.resetSelection(clearAdapter) searchResultAdapter.resetSelection(clearAdapter)
@@ -265,6 +281,7 @@ class FindStationDialog (
/* Display the "No Results" error - hide other unneeded views */ /* Display the "No Results" error - hide other unneeded views */
private fun showNoResultsError() { private fun showNoResultsError() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
customPositiveButton?.isEnabled = false
searchRequestProgressIndicator.isGone = true searchRequestProgressIndicator.isGone = true
noSearchResultsTextView.isVisible = true noSearchResultsTextView.isVisible = true
} }
@@ -273,6 +290,7 @@ class FindStationDialog (
/* Display the "No Results" error - hide other unneeded views */ /* Display the "No Results" error - hide other unneeded views */
private fun showProgressIndicator() { private fun showProgressIndicator() {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
customPositiveButton?.isEnabled = false
searchRequestProgressIndicator.isVisible = true searchRequestProgressIndicator.isVisible = true
noSearchResultsTextView.isGone = true noSearchResultsTextView.isGone = true
} }
@@ -0,0 +1,86 @@
package com.michatec.radio.dialogs
import android.content.Context
import android.view.LayoutInflater
import android.widget.RadioButton
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat.getString
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.michatec.radio.R
import com.michatec.radio.helpers.PreferencesHelper
/*
* PresetSelectionDialog class
*/
class PresetSelectionDialog(private var presetSelectionDialogListener: PresetSelectionDialogListener) {
/* Interface used to communicate back to activity */
interface PresetSelectionDialogListener {
fun onPresetSelectionDialog(dialogResult: Boolean, selectedPreset: String)
}
/* Main class variables */
private lateinit var dialog: AlertDialog
/* Construct and show dialog */
fun show(context: Context) {
// prepare dialog builder
val builder = MaterialAlertDialogBuilder(context)
// inflate custom layout
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_preset_selection, null)
// find radio buttons
val radioGroup = view.findViewById<android.widget.RadioGroup>(R.id.preset_radio_group)
val radioNone = view.findViewById<RadioButton>(R.id.radio_preset_none)
val radioRock = view.findViewById<RadioButton>(R.id.radio_preset_rock)
val radioPop = view.findViewById<RadioButton>(R.id.radio_preset_pop)
val radioJazz = view.findViewById<RadioButton>(R.id.radio_preset_jazz)
val radioFlat = view.findViewById<RadioButton>(R.id.radio_preset_flat)
// set current selection
val currentPreset = PreferencesHelper.loadSelectedPreset()
when (currentPreset) {
"" -> radioNone.isChecked = true
getString(context, R.string.pref_preset_rock) -> radioRock.isChecked = true
getString(context, R.string.pref_preset_pop) -> radioPop.isChecked = true
getString(context, R.string.pref_preset_jazz) -> radioJazz.isChecked = true
getString(context, R.string.pref_preset_flat) -> radioFlat.isChecked = true
else -> radioNone.isChecked = true
}
// set up radio group listener
radioGroup.setOnCheckedChangeListener { _, checkedId ->
val selectedPreset = when (checkedId) {
R.id.radio_preset_none -> ""
R.id.radio_preset_rock -> getString(context, R.string.pref_preset_rock)
R.id.radio_preset_pop -> getString(context, R.string.pref_preset_pop)
R.id.radio_preset_jazz -> getString(context, R.string.pref_preset_jazz)
R.id.radio_preset_flat -> getString(context, R.string.pref_preset_flat)
else -> ""
}
// save preset selection to preferences
PreferencesHelper.saveSelectedPreset(selectedPreset)
// notify listener
presetSelectionDialogListener.onPresetSelectionDialog(true, selectedPreset)
// dismiss dialog
dialog.dismiss()
}
// set custom view
builder.setView(view)
// handle outside-click as cancel
builder.setOnCancelListener {
presetSelectionDialogListener.onPresetSelectionDialog(false, "")
}
// display dialog
dialog = builder.create()
dialog.show()
}
}
@@ -0,0 +1,89 @@
package com.michatec.radio.dialogs
import android.content.Context
import android.view.LayoutInflater
import android.widget.RadioButton
import androidx.appcompat.app.AlertDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.michatec.radio.Keys
import com.michatec.radio.R
import com.michatec.radio.helpers.AppThemeHelper
import com.michatec.radio.helpers.PreferencesHelper
/*
* ThemeSelectionDialog class
*/
class ThemeSelectionDialog(private var themeSelectionDialogListener: ThemeSelectionDialogListener) {
/* Interface used to communicate back to activity */
interface ThemeSelectionDialogListener {
fun onThemeSelectionDialog(dialogResult: Boolean, selectedTheme: String) {
}
}
/* Main class variables */
private lateinit var dialog: AlertDialog
/* Construct and show dialog */
fun show(context: Context) {
// prepare dialog builder
val builder = MaterialAlertDialogBuilder(context)
// inflate custom layout
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_theme_selection, null)
// find radio buttons
val radioGroup = view.findViewById<android.widget.RadioGroup>(R.id.theme_radio_group)
val radioFollowSystem = view.findViewById<RadioButton>(R.id.radio_theme_follow_system)
val radioLight = view.findViewById<RadioButton>(R.id.radio_theme_light)
val radioDark = view.findViewById<RadioButton>(R.id.radio_theme_dark)
// set current selection
val currentTheme = AppThemeHelper.getCurrentTheme(context)
when (currentTheme) {
context.getString(R.string.pref_theme_selection_mode_device_default) -> {
radioFollowSystem.isChecked = true
}
context.getString(R.string.pref_theme_selection_mode_light) -> {
radioLight.isChecked = true
}
context.getString(R.string.pref_theme_selection_mode_dark) -> {
radioDark.isChecked = true
}
}
// set up radio group listener
radioGroup.setOnCheckedChangeListener { _, checkedId ->
val selectedTheme = when (checkedId) {
R.id.radio_theme_follow_system -> Keys.STATE_THEME_FOLLOW_SYSTEM
R.id.radio_theme_light -> Keys.STATE_THEME_LIGHT_MODE
R.id.radio_theme_dark -> Keys.STATE_THEME_DARK_MODE
else -> Keys.STATE_THEME_FOLLOW_SYSTEM
}
// save theme selection to preferences
PreferencesHelper.saveThemeSelection(selectedTheme)
// apply theme immediately
AppThemeHelper.setTheme(selectedTheme)
// notify listener
themeSelectionDialogListener.onThemeSelectionDialog(true, selectedTheme)
// dismiss dialog
dialog.dismiss()
}
// set custom view
builder.setView(view)
// handle outside-click as cancel
builder.setOnCancelListener {
themeSelectionDialogListener.onThemeSelectionDialog(false, Keys.STATE_THEME_FOLLOW_SYSTEM)
}
// display dialog
dialog = builder.create()
dialog.show()
}
}
@@ -1,17 +1,3 @@
/*
* YesNoDialog
* Implements the YesNoDialog class
* A YesNoDialog asks the user if he/she wants to do something or not
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.dialogs package com.michatec.radio.dialogs
import android.content.Context import android.content.Context
@@ -1,18 +1,3 @@
/*
* ArrayListExt.kt
* Implements the ArrayListExt extension methods
* Useful extension methods for ArrayLists
* Source: https://raw.githubusercontent.com/googlesamples/android-UniversalMusicPlayer/master/common/src/main/java/com/example/android/uamp/media/extensions/MediaMetadataCompatExt.kt
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.extensions package com.michatec.radio.extensions
@@ -1,22 +1,7 @@
/*
* MediaControllerExt.kt
* Implements the MediaControllerExt extension methods
* Useful extension methods for MediaController
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.extensions package com.michatec.radio.extensions
import android.content.Context import android.content.Context
import android.os.Bundle import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.media3.session.MediaController import androidx.media3.session.MediaController
import androidx.media3.session.SessionCommand import androidx.media3.session.SessionCommand
import androidx.media3.session.SessionResult import androidx.media3.session.SessionResult
@@ -50,7 +35,7 @@ fun MediaController.requestSleepTimerRemaining(): ListenableFuture<SessionResult
} }
/* Request sleep timer remaining */ /* Request metadata history */
fun MediaController.requestMetadataHistory(): ListenableFuture<SessionResult> { fun MediaController.requestMetadataHistory(): ListenableFuture<SessionResult> {
return sendCustomCommand( return sendCustomCommand(
SessionCommand(Keys.CMD_REQUEST_METADATA_HISTORY, Bundle.EMPTY), SessionCommand(Keys.CMD_REQUEST_METADATA_HISTORY, Bundle.EMPTY),
@@ -58,6 +43,14 @@ fun MediaController.requestMetadataHistory(): ListenableFuture<SessionResult> {
) )
} }
/* Request visualizer data */
fun MediaController.requestVisualizerData(): ListenableFuture<SessionResult> {
return sendCustomCommand(
SessionCommand(Keys.CMD_GET_VISUALIZER_DATA, Bundle.EMPTY),
Bundle.EMPTY
)
}
/* Starts playback with a new media item */ /* Starts playback with a new media item */
fun MediaController.play(context: Context, station: Station) { fun MediaController.play(context: Context, station: Station) {
@@ -71,8 +64,11 @@ fun MediaController.play(context: Context, station: Station) {
/* Starts playback with of a stream url */ /* Starts playback with of a stream url */
fun MediaController.playStreamDirectly(streamUri: String) { fun MediaController.playStreamDirectly(streamUri: String) {
val bundle = Bundle().apply {
putString(Keys.KEY_STREAM_URI, streamUri)
}
sendCustomCommand( sendCustomCommand(
SessionCommand(Keys.CMD_PLAY_STREAM, Bundle.EMPTY), SessionCommand(Keys.CMD_PLAY_STREAM, Bundle.EMPTY),
bundleOf(Pair(Keys.KEY_STREAM_URI, streamUri)) bundle
) )
} }
@@ -1,25 +1,7 @@
/*
* AppThemeHelper.kt
* Implements the AppThemeHelper object
* A AppThemeHelper can set the different app themes: Light Mode, Dark Mode, Follow System
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
import android.content.res.TypedArray
import android.util.Log import android.util.Log
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import com.michatec.radio.Keys import com.michatec.radio.Keys
import com.michatec.radio.R import com.michatec.radio.R
@@ -33,8 +15,6 @@ object AppThemeHelper {
/* Define log tag */ /* Define log tag */
private val TAG: String = AppThemeHelper::class.java.simpleName private val TAG: String = AppThemeHelper::class.java.simpleName
private val sTypedValue = TypedValue()
/* Sets app theme */ /* Sets app theme */
fun setTheme(nightModeState: String) { fun setTheme(nightModeState: String) {
when (nightModeState) { when (nightModeState) {
@@ -76,14 +56,4 @@ object AppThemeHelper {
else -> context.getString(R.string.pref_theme_selection_mode_device_default) else -> context.getString(R.string.pref_theme_selection_mode_device_default)
} }
} }
@ColorInt
fun getColor(context: Context, @AttrRes resource: Int): Int {
val a: TypedArray = context.obtainStyledAttributes(sTypedValue.data, intArrayOf(resource))
val color = a.getColor(0, 0)
a.recycle()
return color
}
} }
@@ -1,23 +1,13 @@
/*
* AudioHelper.kt
* Implements the AudioHelper object
* A AudioHelper provides helper methods for handling audio files
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.util.Log import android.util.Log
import androidx.annotation.OptIn
import androidx.media3.common.Metadata import androidx.media3.common.Metadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.metadata.icy.IcyHeaders import androidx.media3.extractor.metadata.icy.IcyHeaders
import androidx.media3.extractor.metadata.icy.IcyInfo import androidx.media3.extractor.metadata.icy.IcyInfo
import androidx.media3.extractor.metadata.id3.Id3Frame
import androidx.media3.extractor.metadata.id3.TextInformationFrame
import com.michatec.radio.Keys import com.michatec.radio.Keys
import kotlin.math.min import kotlin.math.min
@@ -33,29 +23,53 @@ object AudioHelper {
/* Extract audio stream metadata */ /* Extract audio stream metadata */
@OptIn(UnstableApi::class)
fun getMetadataString(metadata: Metadata): String { fun getMetadataString(metadata: Metadata): String {
var metadataString = String() var title = ""
var artist = ""
var album = ""
for (i in 0 until metadata.length()) { for (i in 0 until metadata.length()) {
// extract IceCast metadata // extract IceCast metadata
when (val entry = metadata.get(i)) { when (val entry = metadata.get(i)) {
is IcyInfo -> { is IcyInfo -> {
metadataString = entry.title.toString() title = entry.title.toString()
} }
is IcyHeaders -> { is IcyHeaders -> {
Log.i(TAG, "icyHeaders:" + entry.name + " - " + entry.genre) Log.i(TAG, "icyHeaders:" + entry.name + " - " + entry.genre)
} }
is Id3Frame -> {
when (entry) {
is TextInformationFrame -> {
when (entry.id) {
"TIT2" -> title = entry.values.getOrNull(0) ?: "" // Title
"TPE1" -> artist = entry.values.getOrNull(0) ?: "" // Artist
"TALB" -> album = entry.values.getOrNull(0) ?: "" // Album
}
}
else -> {
Log.d(TAG, "Unhandled ID3 frame: ${entry.javaClass.simpleName}")
}
}
}
else -> { else -> {
Log.w(TAG, "Unsupported metadata received (type = ${entry.javaClass.simpleName})") Log.w(TAG, "Unsupported metadata received (type = ${entry.javaClass.simpleName})")
} }
} }
// TODO implement HLS metadata extraction (Id3Frame / PrivFrame) }
// https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/metadata/Metadata.Entry.html // Build metadata string
var metadataString = title
if (artist.isNotEmpty() && title.isNotEmpty()) {
metadataString = "$artist - $title"
}
if (album.isNotEmpty() && metadataString.isNotEmpty()) {
metadataString += " ($album)"
} }
// ensure a max length of the metadata string // ensure a max length of the metadata string
if (metadataString.isNotEmpty()) { if (metadataString.isNotEmpty()) {
metadataString = metadataString.substring(0, min(metadataString.length, Keys.DEFAULT_MAX_LENGTH_OF_METADATA_ENTRY)) metadataString = metadataString.take(min(metadataString.length, Keys.DEFAULT_MAX_LENGTH_OF_METADATA_ENTRY))
} }
return metadataString return metadataString
} }
@@ -1,17 +1,3 @@
/*
* BackupHelper.kt
* Implements the BackupHelper object
* A BackupHelper provides helper methods for backing up and restoring the radio station collection
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.ContentResolver import android.content.ContentResolver
@@ -67,7 +53,7 @@ object BackupHelper {
Snackbar.make(view, R.string.toastmessage_restored, Snackbar.LENGTH_LONG).show() Snackbar.make(view, R.string.toastmessage_restored, Snackbar.LENGTH_LONG).show()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
// bypass "ZipException" for Android 14 or above applications when zip file names contain ".." or start with "/" // bypass "ZipException" for Android 14 or above applications when zip file names contain "." or start with "/"
dalvik.system.ZipPathValidator.clearCallback() dalvik.system.ZipPathValidator.clearCallback()
} }
@@ -1,17 +1,3 @@
/*
* CollectionHelper.kt
* Implements the CollectionHelper object
* A CollectionHelper provides helper methods for the collection of stations
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
@@ -288,32 +274,6 @@ object CollectionHelper {
} }
/* Gets MediaIem for next station within collection */
fun getNextMediaItem(context: Context, collection: Collection, stationUuid: String): MediaItem {
val currentStationPosition: Int = getStationPosition(collection, stationUuid)
return if (collection.stations.isEmpty() || currentStationPosition == -1) {
buildMediaItem(context, Station())
} else if (currentStationPosition < collection.stations.size -1) {
buildMediaItem(context, collection.stations[currentStationPosition + 1])
} else {
buildMediaItem(context, collection.stations.first())
}
}
/* Gets MediaIem for previous station within collection */
fun getPreviousMediaItem(context: Context, collection: Collection, stationUuid: String): MediaItem {
val currentStationPosition: Int = getStationPosition(collection, stationUuid)
return if (collection.stations.isEmpty() || currentStationPosition == -1) {
buildMediaItem(context, Station())
} else if (currentStationPosition > 0) {
buildMediaItem(context, collection.stations[currentStationPosition - 1])
} else {
buildMediaItem(context, collection.stations.last())
}
}
/* Get the position from collection for given UUID */ /* Get the position from collection for given UUID */
fun getStationPosition(collection: Collection, stationUuid: String): Int { fun getStationPosition(collection: Collection, stationUuid: String): Int {
collection.stations.forEachIndexed { stationId, station -> collection.stations.forEachIndexed { stationId, station ->
@@ -339,7 +299,7 @@ object CollectionHelper {
} }
/* Returns the children stations under under root (simple media library structure: root > stations) */ /* Returns the children stations under root (simple media library structure: root > stations) */
fun getChildren(context: Context, collection: Collection): List<MediaItem> { fun getChildren(context: Context, collection: Collection): List<MediaItem> {
val mediaItems: MutableList<MediaItem> = mutableListOf() val mediaItems: MutableList<MediaItem> = mutableListOf()
collection.stations.forEach { station -> collection.stations.forEach { station ->
@@ -561,7 +521,7 @@ object CollectionHelper {
fun exportCollectionM3u(context: Context, collection: Collection) { fun exportCollectionM3u(context: Context, collection: Collection) {
Log.v(TAG, "Exporting collection of stations as M3U") Log.v(TAG, "Exporting collection of stations as M3U")
// export collection as M3U - launch = fire & forget (no return value from save collection) // export collection as M3U - launch = fire & forget (no return value from save collection)
if (collection.stations.size > 0) { if (collection.stations.isNotEmpty()) {
CoroutineScope(IO).launch { CoroutineScope(IO).launch {
FileHelper.backupCollectionAsM3uSuspended( FileHelper.backupCollectionAsM3uSuspended(
context, context,
@@ -603,7 +563,7 @@ object CollectionHelper {
fun exportCollectionPls(context: Context, collection: Collection) { fun exportCollectionPls(context: Context, collection: Collection) {
Log.v(TAG, "Exporting collection of stations as PLS") Log.v(TAG, "Exporting collection of stations as PLS")
// export collection as PLS - launch = fire & forget (no return value from save collection) // export collection as PLS - launch = fire & forget (no return value from save collection)
if (collection.stations.size > 0) { if (collection.stations.isNotEmpty()) {
CoroutineScope(IO).launch { CoroutineScope(IO).launch {
FileHelper.backupCollectionAsPlsSuspended( FileHelper.backupCollectionAsPlsSuspended(
context, context,
@@ -670,76 +630,38 @@ object CollectionHelper {
LocalBroadcastManager.getInstance(context).sendBroadcast(collectionChangedIntent) LocalBroadcastManager.getInstance(context).sendBroadcast(collectionChangedIntent)
} }
// /* Creates MediaMetadata for a single station - used in media session*/
// fun buildStationMediaMetadata(context: Context, station: Station, metadata: String): MediaMetadataCompat {
// return MediaMetadataCompat.Builder().apply {
// putString(MediaMetadataCompat.METADATA_KEY_ARTIST, station.name)
// putString(MediaMetadataCompat.METADATA_KEY_TITLE, metadata)
// putString(MediaMetadataCompat.METADATA_KEY_ALBUM, context.getString(R.string.app_name))
// putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, station.getStreamUri())
// putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, ImageHelper.getScaledStationImage(context, station.image, Keys.SIZE_COVER_LOCK_SCREEN))
// //putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, station.image)
// }.build()
// }
//
//
// /* Creates MediaItem for a station - used by collection provider */
// fun buildStationMediaMetaItem(context: Context, station: Station): MediaBrowserCompat.MediaItem {
// val mediaDescriptionBuilder = MediaDescriptionCompat.Builder()
// mediaDescriptionBuilder.setMediaId(station.uuid)
// mediaDescriptionBuilder.setTitle(station.name)
// mediaDescriptionBuilder.setIconBitmap(ImageHelper.getScaledStationImage(context, station.image, Keys.SIZE_COVER_LOCK_SCREEN))
// // mediaDescriptionBuilder.setIconUri(station.image.toUri())
// return MediaBrowserCompat.MediaItem(mediaDescriptionBuilder.build(), MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
// }
//
//
// /* Creates description for a station - used in MediaSessionConnector */
// fun buildStationMediaDescription(context: Context, station: Station, metadata: String): MediaDescriptionCompat {
// val coverBitmap: Bitmap = ImageHelper.getScaledStationImage(context, station.image, Keys.SIZE_COVER_LOCK_SCREEN)
// val extras: Bundle = Bundle()
// extras.putParcelable(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, coverBitmap)
// extras.putParcelable(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, coverBitmap)
// return MediaDescriptionCompat.Builder().apply {
// setMediaId(station.uuid)
// setIconBitmap(coverBitmap)
// setIconUri(station.image.toUri())
// setTitle(metadata)
// setSubtitle(station.name)
// setExtras(extras)
// }.build()
// }
/* Creates a MediaItem with MediaMetadata for a single radio station - used to prepare player */ /* Creates a MediaItem with MediaMetadata for a single radio station - used to prepare player */
fun buildMediaItem(context: Context, station: Station): MediaItem { fun buildMediaItem(context: Context, station: Station): MediaItem {
// todo implement HLS MediaItems
// put uri in RequestMetadata - credit: https://stackoverflow.com/a/70103460 // put uri in RequestMetadata - credit: https://stackoverflow.com/a/70103460
val requestMetadata = MediaItem.RequestMetadata.Builder().apply { val requestMetadata = MediaItem.RequestMetadata.Builder().apply {
setMediaUri(station.getStreamUri().toUri()) setMediaUri(station.getStreamUri().toUri())
}.build() }.build()
// build MediaMetadata // build MediaMetadata
val mediaMetadata = MediaMetadata.Builder().apply { val mediaMetadata = MediaMetadata.Builder().apply {
setTitle(station.name)
setArtist(station.name) setArtist(station.name)
//setTitle(station.name)
// Set artwork URI for casting (remote devices need a public URL)
if (station.remoteImageLocation.isNotEmpty()) {
setArtworkUri(station.remoteImageLocation.toUri())
}
/* check for "file://" prevents a crash when an old backup was restored */ /* check for "file://" prevents a crash when an old backup was restored */
if (station.image.isNotEmpty() && station.image.startsWith("file://")) { if (station.image.isNotEmpty() && station.image.startsWith("file://")) {
//setArtworkUri(station.image.toUri())
setArtworkData(station.image.toUri().toFile().readBytes(), MediaMetadata.PICTURE_TYPE_FRONT_COVER) setArtworkData(station.image.toUri().toFile().readBytes(), MediaMetadata.PICTURE_TYPE_FRONT_COVER)
} else { } else {
//setArtworkUri(Uri.parse(Keys.LOCATION_RESOURCES + R.raw.ic_default_station_image))
setArtworkData(ImageHelper.getStationImageAsByteArray(context), MediaMetadata.PICTURE_TYPE_FRONT_COVER) setArtworkData(ImageHelper.getStationImageAsByteArray(context), MediaMetadata.PICTURE_TYPE_FRONT_COVER)
} }
setIsBrowsable(false) setIsBrowsable(false)
setIsPlayable(true) setIsPlayable(true)
setMediaType(MediaMetadata.MEDIA_TYPE_RADIO_STATION)
}.build() }.build()
// build MediaItem and return it // build MediaItem and return it
return MediaItem.Builder().apply { return MediaItem.Builder().apply {
setMediaId(station.uuid) setMediaId(station.uuid)
setRequestMetadata(requestMetadata) setRequestMetadata(requestMetadata)
setMediaMetadata(mediaMetadata) setMediaMetadata(mediaMetadata)
//setMimeType(station.getMediaType()) setMimeType(station.getMediaType())
setUri(station.getStreamUri().toUri()) setUri(station.getStreamUri().toUri())
}.build() }.build()
} }
@@ -1,17 +1,3 @@
/*
* DateTimeHelper.kt
* Implements the DateTimeHelper object
* A DateTimeHelper provides helper methods for converting Date and Time objects
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.util.Log import android.util.Log
@@ -31,14 +17,14 @@ object DateTimeHelper {
/* Main class variables */ /* Main class variables */
private const val pattern: String = "EEE, dd MMM yyyy HH:mm:ss Z" private const val PATTERN: String = "EEE, dd MMM yyyy HH:mm:ss Z"
private val dateFormat: SimpleDateFormat = SimpleDateFormat(pattern, Locale.ENGLISH) private val dateFormat: SimpleDateFormat = SimpleDateFormat(PATTERN, Locale.ENGLISH)
/* Converts RFC 2822 string representation of a date to DATE */ /* Converts RFC 2822 string representation of a date to DATE */
fun convertFromRfc2822(dateString: String): Date { fun convertFromRfc2822(dateString: String): Date {
val date: Date = try { val date: Date = try {
// parse date string using standard pattern // parse date string using standard PATTERN
dateFormat.parse((dateString)) ?: Keys.DEFAULT_DATE dateFormat.parse((dateString)) ?: Keys.DEFAULT_DATE
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "Unable to parse. Trying an alternative Date format. $e") Log.w(TAG, "Unable to parse. Trying an alternative Date format. $e")
@@ -51,7 +37,7 @@ object DateTimeHelper {
/* Converts a DATE to its RFC 2822 string representation */ /* Converts a DATE to its RFC 2822 string representation */
fun convertToRfc2822(date: Date): String { fun convertToRfc2822(date: Date): String {
val dateFormat = SimpleDateFormat(pattern, Locale.ENGLISH) val dateFormat = SimpleDateFormat(PATTERN, Locale.ENGLISH)
return dateFormat.format(date) return dateFormat.format(date)
} }
@@ -1,17 +1,3 @@
/*
* DownloadFinishedReceiver.kt
* Implements the DownloadFinishedReceiver class
* A DownloadFinishedReceiver listens for finished downloads
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.app.DownloadManager import android.app.DownloadManager
@@ -1,17 +1,3 @@
/*
* DownloadHelper.kt
* Implements the DownloadHelper object
* A DownloadHelper provides helper methods for downloading files
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.app.DownloadManager import android.app.DownloadManager
@@ -384,7 +370,7 @@ object DownloadHelper {
private fun determineAllowedNetworkTypes(type: Int, ignoreWifiRestriction: Boolean): Int { private fun determineAllowedNetworkTypes(type: Int, ignoreWifiRestriction: Boolean): Int {
var allowedNetworkTypes: Int = var allowedNetworkTypes: Int =
(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE) (DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
// restrict download of audio files to WiFi if necessary // restrict download of audio files to Wi-Fi if necessary
if (type == Keys.FILE_TYPE_AUDIO) { if (type == Keys.FILE_TYPE_AUDIO) {
if (!ignoreWifiRestriction && !PreferencesHelper.downloadOverMobile()) { if (!ignoreWifiRestriction && !PreferencesHelper.downloadOverMobile()) {
allowedNetworkTypes = DownloadManager.Request.NETWORK_WIFI allowedNetworkTypes = DownloadManager.Request.NETWORK_WIFI
@@ -0,0 +1,117 @@
package com.michatec.radio.helpers
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.michatec.radio.R
class ExtrasHelper {
companion object {
private const val TAG = "ExtrasHelper"
init {
try {
System.loadLibrary("extra")
} catch (e: Exception) {
Log.e(TAG, "Failed to load extra library", e)
}
}
@JvmStatic
private external fun visualize(surface: Surface, data: FloatArray)
fun render(surface: Surface, data: FloatArray) {
if (!surface.isValid) return
try {
visualize(surface, data)
} catch (e: Exception) {
Log.e(TAG, "Native visualize failed", e)
}
}
}
class VisualizerPreference(context: Context, attrs: AttributeSet? = null) : Preference(context, attrs) {
private var visualizerView: VisualizerView? = null
init {
// We can use a standard layout and inject our view
layoutResource = R.layout.preference_visualizer
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
// Try to find the container in the inflated layout
var container = holder.findViewById(R.id.visualizer_container) as? ViewGroup
// Fallback: If not found by ID, maybe the root is the container?
if (container == null && holder.itemView is ViewGroup) {
container = holder.itemView as ViewGroup
}
if (container != null) {
if (visualizerView == null) {
visualizerView = VisualizerView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
}
val currentParent = visualizerView?.parent as? ViewGroup
if (currentParent != container) {
currentParent?.removeView(visualizerView)
// If we injected into a standard preference, don't clear everything, just add
if (container is FrameLayout || container.childCount == 0) {
container.removeAllViews()
}
container.addView(visualizerView)
}
} else {
Log.e("VisualizerPreference", "Could not find any container to attach VisualizerView!")
}
}
fun update(data: FloatArray) {
visualizerView?.update(data)
}
}
class VisualizerView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback {
private var surface: Surface? = null
init {
Log.d("VisualizerView", "VisualizerView initialized")
holder.addCallback(this)
}
fun update(data: FloatArray) {
val s = surface
if (s != null && s.isValid) {
render(s, data)
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
surface = holder.surface
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
surface = holder.surface
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
surface = null
}
}
}
@@ -1,17 +1,3 @@
/*
* FileHelper.kt
* Implements the FileHelper object
* A FileHelper provides helper methods for reading and writing files from and to device storage
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.app.Activity import android.app.Activity
@@ -33,7 +19,6 @@ import kotlinx.coroutines.Dispatchers.IO
import java.io.* import java.io.*
import java.util.* import java.util.*
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/* /*
@@ -246,7 +231,7 @@ object FileHelper {
File(activity.getExternalFilesDir(Keys.FOLDER_COLLECTION), Keys.COLLECTION_M3U_FILE) File(activity.getExternalFilesDir(Keys.FOLDER_COLLECTION), Keys.COLLECTION_M3U_FILE)
if (!m3uFile.exists()) { if (!m3uFile.exists()) {
m3uFile = File( m3uFile = File(
activity.getExternalFilesDir(Keys.URLRADIO_LEGACY_FOLDER_COLLECTION), activity.getExternalFilesDir(Keys.RADIO_LEGACY_FOLDER_COLLECTION),
Keys.COLLECTION_M3U_FILE Keys.COLLECTION_M3U_FILE
) )
} }
@@ -270,7 +255,7 @@ object FileHelper {
File(activity.getExternalFilesDir(Keys.FOLDER_COLLECTION), Keys.COLLECTION_PLS_FILE) File(activity.getExternalFilesDir(Keys.FOLDER_COLLECTION), Keys.COLLECTION_PLS_FILE)
if (!plsFile.exists()) { if (!plsFile.exists()) {
plsFile = File( plsFile = File(
activity.getExternalFilesDir(Keys.URLRADIO_LEGACY_FOLDER_COLLECTION), activity.getExternalFilesDir(Keys.RADIO_LEGACY_FOLDER_COLLECTION),
Keys.COLLECTION_PLS_FILE Keys.COLLECTION_PLS_FILE
) )
} }
@@ -292,7 +277,7 @@ object FileHelper {
collection: Collection, collection: Collection,
lastUpdate: Date lastUpdate: Date
) { ) {
return suspendCoroutine { cont -> return suspendCancellableCoroutine { cont ->
cont.resume(saveCollection(context, collection, lastUpdate)) cont.resume(saveCollection(context, collection, lastUpdate))
} }
} }
@@ -311,7 +296,7 @@ object FileHelper {
originalFileUri: Uri, originalFileUri: Uri,
targetFileUri: Uri targetFileUri: Uri
): Boolean { ): Boolean {
return suspendCoroutine { cont -> return suspendCancellableCoroutine { cont ->
cont.resume(copyFile(context, originalFileUri, targetFileUri)) cont.resume(copyFile(context, originalFileUri, targetFileUri))
} }
} }
@@ -319,7 +304,7 @@ object FileHelper {
/* Suspend function: Exports collection of stations as M3U file - local backup copy */ /* Suspend function: Exports collection of stations as M3U file - local backup copy */
suspend fun backupCollectionAsM3uSuspended(context: Context, collection: Collection) { suspend fun backupCollectionAsM3uSuspended(context: Context, collection: Collection) {
return suspendCoroutine { cont -> return suspendCancellableCoroutine { cont ->
Log.v(TAG, "Backing up collection as M3U - Thread: ${Thread.currentThread().name}") Log.v(TAG, "Backing up collection as M3U - Thread: ${Thread.currentThread().name}")
// create M3U string // create M3U string
val m3uString: String = CollectionHelper.createM3uString(collection) val m3uString: String = CollectionHelper.createM3uString(collection)
@@ -338,7 +323,7 @@ object FileHelper {
/* Suspend function: Exports collection of stations as PLS file - local backup copy */ /* Suspend function: Exports collection of stations as PLS file - local backup copy */
suspend fun backupCollectionAsPlsSuspended(context: Context, collection: Collection) { suspend fun backupCollectionAsPlsSuspended(context: Context, collection: Collection) {
return suspendCoroutine { cont -> return suspendCancellableCoroutine { cont ->
Log.v(TAG, "Backing up collection as PLS - Thread: ${Thread.currentThread().name}") Log.v(TAG, "Backing up collection as PLS - Thread: ${Thread.currentThread().name}")
// create PLS string // create PLS string
val plsString: String = CollectionHelper.createPlsString(collection) val plsString: String = CollectionHelper.createPlsString(collection)
@@ -417,16 +402,14 @@ object FileHelper {
/* Reads InputStream from file uri and returns it as String */ /* Reads InputStream from file uri and returns it as String */
private fun readTextFileFromFile(context: Context): String { private fun readTextFileFromFile(context: Context): String {
// todo read https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html
// https://developer.android.com/training/secure-file-sharing/retrieve-info
// check if file exists // check if file exists
val file = File(context.getExternalFilesDir(Keys.FOLDER_COLLECTION), Keys.COLLECTION_FILE) val file = File(context.getExternalFilesDir(Keys.FOLDER_COLLECTION), Keys.COLLECTION_FILE)
if (!file.exists() || !file.canRead()) { if (!file.exists() || !file.canRead()) {
return String() return String()
} }
// read until last line reached // read until last line reached
val stream: InputStream = file.inputStream() val uri = Uri.fromFile(file)
val stream: InputStream = context.contentResolver.openInputStream(uri) ?: return String()
val reader = BufferedReader(InputStreamReader(stream)) val reader = BufferedReader(InputStreamReader(stream))
val builder: StringBuilder = StringBuilder() val builder: StringBuilder = StringBuilder()
reader.forEachLine { reader.forEachLine {
@@ -1,17 +1,3 @@
/*
* ImageHelper.kt
* Implements the ImageHelper object
* An ImageHelper provides helper methods for image related operations
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
@@ -25,6 +11,7 @@ import com.michatec.radio.R
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import java.io.IOException import java.io.IOException
import java.io.InputStream import java.io.InputStream
import androidx.core.graphics.createBitmap
/* /*
@@ -98,7 +85,7 @@ object ImageHelper {
} }
// create empty bitmap and canvas // create empty bitmap and canvas
val outputImage: Bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val outputImage: Bitmap = createBitmap(size, size, Bitmap.Config.ARGB_8888)
val imageCanvas = Canvas(outputImage) val imageCanvas = Canvas(outputImage)
// draw square background // draw square background
@@ -1,42 +0,0 @@
/*
* ImportHelper.kt
* Implements the ImportHelper object
* A ImportHelper provides methods for integrating station files from Radio v3
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers
import android.content.Context
import com.michatec.radio.Keys
import com.michatec.radio.core.Collection
/*
* ImportHelper object
*/
object ImportHelper {
/* */
fun removeDefaultStationImageUris(context: Context) {
val collection: Collection = FileHelper.readCollection(context)
collection.stations.forEach { station ->
if (station.image == Keys.LOCATION_DEFAULT_STATION_IMAGE) {
station.image = String()
}
if (station.smallImage == Keys.LOCATION_DEFAULT_STATION_IMAGE) {
station.smallImage = String()
}
}
CollectionHelper.saveCollection(context, collection, async = false)
}
}
@@ -0,0 +1,25 @@
package com.michatec.radio.helpers
import android.content.Context
import android.text.TextUtils
import android.widget.TextView
import androidx.preference.PreferenceViewHolder
import androidx.preference.SwitchPreferenceCompat
/*
* Custom SwitchPreferenceCompat that enables marquee (scrolling text) for the title
*/
class MarqueeSwitchPreference(context: Context) : SwitchPreferenceCompat(context) {
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val title = holder.findViewById(android.R.id.title) as? TextView
title?.apply {
ellipsize = TextUtils.TruncateAt.MARQUEE
setSingleLine(true)
marqueeRepeatLimit = -1 // Repeat indefinitely
isSelected = true // Required for marquee to start
setHorizontallyScrolling(true)
}
}
}
@@ -0,0 +1,129 @@
package com.michatec.radio.helpers
import android.util.Log
import androidx.annotation.OptIn
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.common.audio.AudioProcessor.AudioFormat
import androidx.media3.common.audio.BaseAudioProcessor
import androidx.media3.common.util.UnstableApi
import java.nio.ByteBuffer
import java.nio.ByteOrder
@OptIn(UnstableApi::class)
class NativeAudioProcessor : BaseAudioProcessor() {
companion object {
private const val TAG = "NativeAudioProcessor"
init {
try {
System.loadLibrary("dsp")
} catch (e: Exception) {
Log.e(TAG, "Failed to load dsp library", e)
}
}
}
private var directBuffer: ByteBuffer? = null
// ===== JNI =====
private external fun setSampleRate(sampleRate: Float)
private external fun setDrcEnabled(enabled: Boolean)
private external fun setReverbMix(mix: Float)
private external fun setEqFull(gains: FloatArray)
private external fun setBassBoost(gainDb: Float)
private external fun setStereoWidth(width: Float)
private external fun processAudioDirect(buf: ByteBuffer, size: Int)
private external fun getFftData(): FloatArray
// ===== API =====
fun enableDrc(enabled: Boolean) = setDrcEnabled(enabled)
fun setReverb(mix: Float) = setReverbMix(mix)
fun setEqAll(gains: FloatArray) = setEqFull(gains)
fun enableBassBoost(gainDb: Float) = setBassBoost(gainDb)
fun setWidth(width: Float) = setStereoWidth(width)
fun getVisualizer(): FloatArray {
val raw = getFftData()
val out = FloatArray(raw.size)
for (i in raw.indices) out[i] = kotlin.math.log10(1f + raw[i])
return out
}
// ===== AudioProcessor Overrides =====
override fun onConfigure(inputAudioFormat: AudioFormat): AudioFormat {
// Always try to support the input format if it is PCM 16-bit
if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT) {
Log.e(TAG, "Unsupported encoding: ${inputAudioFormat.encoding}")
throw AudioProcessor.UnhandledAudioFormatException(inputAudioFormat)
}
// Pass the actual sample rate to native
setSampleRate(inputAudioFormat.sampleRate.toFloat())
return inputAudioFormat
}
override fun queueInput(inputBuffer: ByteBuffer) {
val size = inputBuffer.remaining()
if (size == 0) return
val bufferToProcess: ByteBuffer
if (inputBuffer.isDirect) {
bufferToProcess = inputBuffer
} else {
if (directBuffer == null || directBuffer!!.capacity() < size) {
directBuffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())
}
directBuffer!!.clear()
inputBuffer.position()
directBuffer!!.put(inputBuffer)
directBuffer!!.flip()
bufferToProcess = directBuffer!!
}
processAudioDirect(bufferToProcess, size)
val out = replaceOutputBuffer(size)
out.order(ByteOrder.nativeOrder())
bufferToProcess.position(0)
out.put(bufferToProcess)
out.flip()
}
override fun onReset() {
super.onReset()
directBuffer = null
}
// ===== Presets =====
fun setPresetRock() {
enableDrc(true)
setReverb(0.26f)
setWidth(1.1f)
setEqAll(floatArrayOf(2f, 1f, 0f, -1f, -1f, 0f, 1f, 2f, 2f, 3f))
enableBassBoost(0.9f)
}
fun setPresetPop() {
enableDrc(true)
setReverb(0.18f)
setWidth(1.05f)
setEqAll(floatArrayOf(0f, 1f, 1f, 1f, 0f, 0f, 1f, 2f, 2f, 1f))
enableBassBoost(0.6f)
}
fun setPresetJazz() {
enableDrc(false)
setReverb(0.15f)
setWidth(0.8f)
setEqAll(floatArrayOf(0f, 0f, 1f, 1f, 0f, 0f, 1f, 1f, 0f, 0f))
enableBassBoost(0.2f)
}
fun setPresetFlat() {
enableDrc(false)
setReverb(0f)
setWidth(1f)
setEqAll(FloatArray(10))
enableBassBoost(0f)
}
}
@@ -1,17 +1,3 @@
/*
* NetworkHelper.kt
* Implements the NetworkHelper object
* A NetworkHelper provides helper methods for network related operations
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
@@ -19,13 +5,13 @@ import android.net.ConnectivityManager
import android.net.Network import android.net.Network
import android.util.Log import android.util.Log
import com.michatec.radio.Keys import com.michatec.radio.Keys
import kotlinx.coroutines.suspendCancellableCoroutine
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.InetAddress import java.net.InetAddress
import java.net.URL import java.net.URL
import java.net.UnknownHostException import java.net.UnknownHostException
import java.util.* import java.util.*
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/* /*
@@ -105,7 +91,7 @@ object NetworkHelper {
/* Suspend function: Detects content type (mime type) from given URL string - async using coroutine */ /* Suspend function: Detects content type (mime type) from given URL string - async using coroutine */
suspend fun detectContentTypeSuspended(urlString: String): ContentType { suspend fun detectContentTypeSuspended(urlString: String): ContentType {
return suspendCoroutine { cont -> return suspendCancellableCoroutine { cont ->
cont.resume(detectContentType(urlString)) cont.resume(detectContentType(urlString))
} }
} }
@@ -113,14 +99,14 @@ object NetworkHelper {
/* Suspend function: Gets a random radio-browser.info api address - async using coroutine */ /* Suspend function: Gets a random radio-browser.info api address - async using coroutine */
suspend fun getRadioBrowserServerSuspended(): String { suspend fun getRadioBrowserServerSuspended(): String {
return suspendCoroutine { cont -> return suspendCancellableCoroutine { cont ->
val serverAddress: String = try { val serverAddress: String = try {
// get all available radio browser servers // get all available radio browser servers
val serverAddressList: Array<InetAddress> = val serverAddressList: Array<InetAddress> =
InetAddress.getAllByName(Keys.RADIO_BROWSER_API_BASE) InetAddress.getAllByName(Keys.RADIO_BROWSER_API_BASE)
// select a random address // select a random address
serverAddressList[Random().nextInt(serverAddressList.size)].canonicalHostName serverAddressList[Random().nextInt(serverAddressList.size)].canonicalHostName
} catch (e: UnknownHostException) { } catch (_: UnknownHostException) {
Keys.RADIO_BROWSER_API_DEFAULT Keys.RADIO_BROWSER_API_DEFAULT
} }
PreferencesHelper.saveRadioBrowserApiAddress(serverAddress) PreferencesHelper.saveRadioBrowserApiAddress(serverAddress)
@@ -129,7 +115,7 @@ object NetworkHelper {
} }
/* Creates a http connection from given url string */ /* Creates an http connection from given url string */
private fun createConnection(urlString: String, redirectCount: Int = 0): HttpURLConnection? { private fun createConnection(urlString: String, redirectCount: Int = 0): HttpURLConnection? {
var connection: HttpURLConnection? = null var connection: HttpURLConnection? = null
@@ -1,21 +1,8 @@
/*
* PreferencesHelper.kt
* Implements the PreferencesHelper object
* A PreferencesHelper provides helper methods for the saving and loading values from shared preferences
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.util.Log import android.util.Log
import androidx.core.content.edit import androidx.core.content.edit
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
@@ -213,20 +200,6 @@ object PreferencesHelper {
} }
/* Checks if housekeeping work needs to be done - used usually in DownloadWorker "REQUEST_UPDATE_COLLECTION" */
fun isHouseKeepingNecessary(): Boolean {
return sharedPreferences.getBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, true)
}
/* Saves state of housekeeping */
fun saveHouseKeepingNecessaryState(state: Boolean = false) {
sharedPreferences.edit {
putBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, state)
}
}
/* Load currently selected app theme */ /* Load currently selected app theme */
fun loadThemeSelection(): String { fun loadThemeSelection(): String {
return sharedPreferences.getString( return sharedPreferences.getString(
@@ -236,23 +209,24 @@ object PreferencesHelper {
} }
/* Loads value of the option: Edit Stations */ /* Save currently selected app theme */
fun loadEditStationsEnabled(): Boolean { fun saveThemeSelection(theme: String) {
return sharedPreferences.getBoolean(Keys.PREF_EDIT_STATIONS, true)
}
/* Saves value of the option: Edit Stations (only needed for migration) */
fun saveEditStationsEnabled(enabled: Boolean = false) {
sharedPreferences.edit { sharedPreferences.edit {
putBoolean(Keys.PREF_EDIT_STATIONS, enabled) putString(Keys.PREF_THEME_SELECTION, theme)
} }
} }
/* Loads value of the option: Edit Stations */
fun loadEditStationsEnabled(context: Context): Boolean {
val defaultValue = !context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
return sharedPreferences.getBoolean(Keys.PREF_EDIT_STATIONS, defaultValue)
}
/* Loads value of the option: Edit Station Streams */ /* Loads value of the option: Edit Station Streams */
fun loadEditStreamUrisEnabled(): Boolean { fun loadEditStreamUrisEnabled(context: Context): Boolean {
return sharedPreferences.getBoolean(Keys.PREF_EDIT_STREAMS_URIS, true) val defaultValue = !context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
return sharedPreferences.getBoolean(Keys.PREF_EDIT_STREAMS_URIS, defaultValue)
} }
@@ -276,8 +250,106 @@ object PreferencesHelper {
fun downloadOverMobile(): Boolean { fun downloadOverMobile(): Boolean {
return sharedPreferences.getBoolean( return sharedPreferences.getBoolean(
Keys.PREF_DOWNLOAD_OVER_MOBILE, Keys.PREF_DOWNLOAD_OVER_MOBILE,
Keys.DEFAULT_DOWNLOAD_OVER_MOBILE false
) )
} }
/* Loads Bass Boost gain */
fun loadBassBoost(): Float {
return if (sharedPreferences.getBoolean(Keys.PREF_BASS_BOOST, false)) 1f else 0.0f
}
/* Loads Reverb mix */
fun loadReverb(): Float {
return if (sharedPreferences.getBoolean(Keys.PREF_REVERB, false)) 0.3f else 0.0f
}
/* Loads DRC enabled state */
fun loadDrcEnabled(): Boolean {
return sharedPreferences.getBoolean(Keys.PREF_DRC, false)
}
/* Loads all EQ bands (10 bands for full range) */
fun loadEqBand(band: Int): Int {
return when (band) {
0 -> sharedPreferences.getInt(Keys.PREF_EQ_LOW, 0)
1 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_1, 0)
2 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_2, 0)
3 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_3, 0)
4 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_4, 0)
5 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_5, 0)
6 -> sharedPreferences.getInt(Keys.PREF_EQ_MID, 0)
7 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_6, 0)
8 -> sharedPreferences.getInt(Keys.PREF_EQ_BAND_7, 0)
9 -> sharedPreferences.getInt(Keys.PREF_EQ_HIGH, 0)
else -> 0
}
}
/* Loads selected preset name */
fun loadSelectedPreset(): String {
return sharedPreferences.getString(Keys.PREF_PRESET_SELECTED, "") ?: ""
}
/* Saves selected preset name */
fun saveSelectedPreset(preset: String) {
sharedPreferences.edit { putString(Keys.PREF_PRESET_SELECTED, preset) }
}
/* Loads preset EQ band values */
fun loadPresetEqBand(band: Int): Int {
return when (band) {
0 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_0, 0)
1 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_1, 0)
2 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_2, 0)
3 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_3, 0)
4 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_4, 0)
5 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_5, 0)
6 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_6, 0)
7 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_7, 0)
8 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_8, 0)
9 -> sharedPreferences.getInt(Keys.PREF_PRESET_EQ_BAND_9, 0)
else -> 0
}
}
/* Loads preset Bass Boost */
fun loadPresetBassBoost(): Float {
return sharedPreferences.getFloat(Keys.PREF_PRESET_BASS_BOOST, 0f)
}
/* Loads preset Reverb */
fun loadPresetReverb(): Float {
return sharedPreferences.getFloat(Keys.PREF_PRESET_REVERB, 0f)
}
/* Loads preset DRC */
fun loadPresetDrc(): Boolean {
return sharedPreferences.getBoolean(Keys.PREF_PRESET_DRC, false)
}
/* Loads preset Stereo Width */
fun loadPresetStereoWidth(): Float {
return sharedPreferences.getFloat(Keys.PREF_PRESET_STEREO_WIDTH, 1f)
}
/* Resets Equalizer settings to default */
fun resetEqualizer() {
sharedPreferences.edit {
putInt(Keys.PREF_EQ_LOW, 0)
putInt(Keys.PREF_EQ_BAND_1, 0)
putInt(Keys.PREF_EQ_BAND_2, 0)
putInt(Keys.PREF_EQ_BAND_3, 0)
putInt(Keys.PREF_EQ_BAND_4, 0)
putInt(Keys.PREF_EQ_BAND_5, 0)
putInt(Keys.PREF_EQ_MID, 0)
putInt(Keys.PREF_EQ_BAND_6, 0)
putInt(Keys.PREF_EQ_BAND_7, 0)
putInt(Keys.PREF_EQ_HIGH, 0)
}
}
} }
@@ -1,23 +1,8 @@
/*
* ShortcutHelper.kt
* Implements the ShortcutHelper object
* A ShortcutHelper creates and handles station shortcuts on the Home screen
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.graphics.Bitmap import android.graphics.Bitmap
import android.os.Build
import android.widget.Toast import android.widget.Toast
import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.content.pm.ShortcutManagerCompat
@@ -36,7 +21,6 @@ object ShortcutHelper {
/* Places shortcut on Home screen */ /* Places shortcut on Home screen */
fun placeShortcut(context: Context, station: Station) { fun placeShortcut(context: Context, station: Station) {
// credit: https://medium.com/@BladeCoder/using-support-library-26-0-0-you-can-do-bb75911e01e8
if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) { if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
val shortcut: ShortcutInfoCompat = ShortcutInfoCompat.Builder(context, station.name) val shortcut: ShortcutInfoCompat = ShortcutInfoCompat.Builder(context, station.name)
.setShortLabel(station.name) .setShortLabel(station.name)
@@ -73,8 +57,8 @@ object ShortcutHelper {
): IconCompat { ): IconCompat {
val stationImageBitmap: Bitmap = val stationImageBitmap: Bitmap =
ImageHelper.getScaledStationImage(context, stationImage.toUri(), 192) ImageHelper.getScaledStationImage(context, stationImage.toUri(), 192)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
IconCompat.createWithAdaptiveBitmap( return IconCompat.createWithAdaptiveBitmap(
ImageHelper.createSquareImage( ImageHelper.createSquareImage(
context, context,
stationImageBitmap, stationImageBitmap,
@@ -83,17 +67,5 @@ object ShortcutHelper {
true true
) )
) )
} else {
IconCompat.createWithAdaptiveBitmap(
ImageHelper.createSquareImage(
context,
stationImageBitmap,
stationImageColor,
192,
false
)
)
} }
} }
}
@@ -1,17 +1,3 @@
/*
* UiHelper.kt
* Implements the UiHelper object
* A UiHelper provides helper methods for User Interface related tasks
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
@@ -1,17 +1,3 @@
/*
* UpdateHelper.kt
* Implements the UpdateHelper class
* A UpdateHelper provides methods to update a single station or the whole collection of stations
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.helpers package com.michatec.radio.helpers
import android.content.Context import android.content.Context
@@ -1,17 +1,3 @@
/*
* DirectInputCheck.kt
* Implements the DirectInputCheck class
* A DirectInputCheck checks if a station url is valid and returns station via a listener
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-23 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.search package com.michatec.radio.search
import android.content.Context import android.content.Context
@@ -1,17 +1,3 @@
/*
* RadioBrowserResult.kt
* Implements the RadioBrowserResult class
* A RadioBrowserResult is the search result of a request to api.radio-browser.info
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.search package com.michatec.radio.search
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
@@ -1,17 +1,3 @@
/*
* RadioBrowserSearch.kt
* Implements the RadioBrowserSearch class
* A RadioBrowserSearch performs searches on the radio-browser.info database
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.search package com.michatec.radio.search
import android.content.Context import android.content.Context
@@ -129,7 +115,7 @@ class RadioBrowserSearch(private var radioBrowserSearchListener: RadioBrowserSea
/* Listens for (positive) server responses to search requests */ /* Listens for (positive) server responses to search requests */
private val responseListener: Response.Listener<JSONArray> = Response.Listener<JSONArray> { response -> private val responseListener: Response.Listener<JSONArray> = Response.Listener { response ->
if (response != null) { if (response != null) {
radioBrowserSearchListener.onRadioBrowserSearchResults(createRadioBrowserResult(response.toString())) radioBrowserSearchListener.onRadioBrowserSearchResults(createRadioBrowserResult(response.toString()))
} }
@@ -1,37 +1,28 @@
/*
* SearchResultAdapter.kt
* Implements the SearchResultAdapter class
* A SearchResultAdapter is a custom adapter providing search result views for a RecyclerView
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.search package com.michatec.radio.search
import android.content.Context import android.content.Context
import android.media.AudioAttributes import android.media.AudioAttributes
import android.media.AudioFocusRequest import android.media.AudioFocusRequest
import android.media.AudioManager import android.media.AudioManager
import android.os.Build
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.Toast import android.widget.Toast
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.media3.common.MediaItem import androidx.media3.common.*
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textview.MaterialTextView import com.google.android.material.textview.MaterialTextView
import com.michatec.radio.R import com.michatec.radio.R
import com.michatec.radio.core.Station import com.michatec.radio.core.Station
import com.michatec.radio.helpers.NativeAudioProcessor
/* /*
@@ -46,6 +37,7 @@ class SearchResultAdapter(
private var exoPlayer: ExoPlayer? = null private var exoPlayer: ExoPlayer? = null
private var paused: Boolean = false private var paused: Boolean = false
private var isItemSelected: Boolean = false private var isItemSelected: Boolean = false
private var nativeAudioProcessor = NativeAudioProcessor()
/* Listener Interface */ /* Listener Interface */
interface SearchResultAdapterListener { interface SearchResultAdapterListener {
@@ -106,7 +98,7 @@ class SearchResultAdapter(
} }
// mark selected if necessary // mark selected if necessary
val isSelected = selectedPosition == holder.adapterPosition val isSelected = selectedPosition == holder.bindingAdapterPosition
searchResultViewHolder.searchResultLayout.isSelected = isSelected searchResultViewHolder.searchResultLayout.isSelected = isSelected
// toggle text scrolling (marquee) if necessary // toggle text scrolling (marquee) if necessary
@@ -121,7 +113,7 @@ class SearchResultAdapter(
searchResultViewHolder.searchResultLayout.setOnClickListener { searchResultViewHolder.searchResultLayout.setOnClickListener {
// move marked position // move marked position
val previousSelectedPosition = selectedPosition val previousSelectedPosition = selectedPosition
selectedPosition = holder.adapterPosition selectedPosition = holder.bindingAdapterPosition
notifyItemChanged(previousSelectedPosition) notifyItemChanged(previousSelectedPosition)
notifyItemChanged(selectedPosition) notifyItemChanged(selectedPosition)
@@ -133,7 +125,7 @@ class SearchResultAdapter(
resetSelection(false) resetSelection(false)
} else { } else {
// get the selected station from searchResults // get the selected station from searchResults
val selectedStation = searchResults[holder.adapterPosition] val selectedStation = searchResults[holder.bindingAdapterPosition]
// perform pre-playback here // perform pre-playback here
performPrePlayback(searchResultViewHolder.searchResultLayout.context, selectedStation.getStreamUri()) performPrePlayback(searchResultViewHolder.searchResultLayout.context, selectedStation.getStreamUri())
// hand over station // hand over station
@@ -153,6 +145,7 @@ class SearchResultAdapter(
} }
@OptIn(UnstableApi::class)
private fun performPrePlayback(context: Context, streamUri: String) { private fun performPrePlayback(context: Context, streamUri: String) {
if (streamUri.contains(".m3u8")) { if (streamUri.contains(".m3u8")) {
// release previous player if it exists // release previous player if it exists
@@ -166,8 +159,30 @@ class SearchResultAdapter(
// release previous player if it exists // release previous player if it exists
stopPrePlayback() stopPrePlayback()
// create a new instance of ExoPlayer // set up audio attributes for the preview player
exoPlayer = ExoPlayer.Builder(context).build() val audioAttributes = androidx.media3.common.AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_MEDIA)
.build()
// Create a RenderersFactory that injects the NativeAudioProcessor
val renderersFactory = object : DefaultRenderersFactory(context) {
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean
): AudioSink? {
return DefaultAudioSink.Builder(context)
.setAudioProcessors(arrayOf(nativeAudioProcessor))
.build()
}
}
// create a new instance of ExoPlayer with focus handling
exoPlayer = ExoPlayer.Builder(context, renderersFactory)
.setAudioAttributes(audioAttributes, true)
.setHandleAudioBecomingNoisy(true)
.build()
// create a MediaItem with the streamUri // create a MediaItem with the streamUri
val mediaItem = MediaItem.fromUri(streamUri) val mediaItem = MediaItem.fromUri(streamUri)
@@ -209,22 +224,16 @@ class SearchResultAdapter(
// stop radio playback when one is active // stop radio playback when one is active
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val audioAttributes = AudioAttributes.Builder() val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA) .setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build() .build()
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT) val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(audioAttributes) .setAudioAttributes(audioAttributes)
.build() .build()
audioManager.requestAudioFocus(focusRequest) audioManager.requestAudioFocus(focusRequest)
} else {
@Suppress("DEPRECATION")
// For older versions where AudioFocusRequest is not available
audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
}
} }
@@ -246,7 +255,7 @@ class SearchResultAdapter(
/* /*
* Inner class: ViewHolder for a radio station search result * Inner class: ViewHolder for a radio station search result
*/ */
private inner class SearchResultViewHolder(var searchResultLayout: View) : private class SearchResultViewHolder(var searchResultLayout: View) :
RecyclerView.ViewHolder(searchResultLayout) { RecyclerView.ViewHolder(searchResultLayout) {
val nameView: MaterialTextView = searchResultLayout.findViewById(R.id.station_name) val nameView: MaterialTextView = searchResultLayout.findViewById(R.id.station_name)
val streamView: MaterialTextView = searchResultLayout.findViewById(R.id.station_url) val streamView: MaterialTextView = searchResultLayout.findViewById(R.id.station_url)
@@ -1,23 +1,11 @@
/*
* LayoutHolder.kt
* Implements the LayoutHolder class
* A LayoutHolder hold references to the main views
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.ui package com.michatec.radio.ui
import android.annotation.SuppressLint
import android.content.ClipData import android.content.ClipData
import android.content.ClipboardManager import android.content.ClipboardManager
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.AnimatedVectorDrawable import android.graphics.drawable.AnimatedVectorDrawable
import android.os.Build import android.os.Build
import android.view.View import android.view.View
@@ -31,9 +19,11 @@ import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.Group import androidx.constraintlayout.widget.Group
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.mediarouter.app.MediaRouteButton
import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.cast.framework.CastButtonFactory
import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
import com.michatec.radio.Keys import com.michatec.radio.Keys
@@ -53,30 +43,33 @@ data class LayoutHolder(var rootView: View) {
/* Main class variables */ /* Main class variables */
var recyclerView: RecyclerView = rootView.findViewById(R.id.station_list) var recyclerView: RecyclerView = rootView.findViewById(R.id.station_list)
val layoutManager: LinearLayoutManager val layoutManager: LinearLayoutManager
private var bottomSheet: ConstraintLayout = rootView.findViewById(R.id.bottom_sheet) private var bottomSheet: ConstraintLayout? = rootView.findViewById(R.id.bottom_sheet)
//private var sheetMetadataViews: Group //private var sheetMetadataViews: Group
private var sleepTimerRunningViews: Group = rootView.findViewById(R.id.sleep_timer_running_views) private var sleepTimerRunningViews: Group? = rootView.findViewById(R.id.sleep_timer_running_views)
private var downloadProgressIndicator: ProgressBar = rootView.findViewById(R.id.download_progress_indicator) private var downloadProgressIndicator: ProgressBar? = rootView.findViewById(R.id.download_progress_indicator)
private var stationImageView: ImageView = rootView.findViewById(R.id.station_icon) private var stationImageView: ImageView? = rootView.findViewById(R.id.station_icon)
private var stationNameView: TextView = rootView.findViewById(R.id.player_station_name) private var stationNameView: TextView? = rootView.findViewById(R.id.player_station_name)
private var metadataView: TextView = rootView.findViewById(R.id.player_station_metadata) private var metadataView: TextView? = rootView.findViewById(R.id.player_station_metadata)
var playButtonView: ImageButton = rootView.findViewById(R.id.player_play_button) var playButtonView: ImageButton = rootView.findViewById(R.id.player_play_button)
var playerPrevButtonView: ImageButton? = rootView.findViewById(R.id.player_prev_button)
var playerNextButtonView: ImageButton? = rootView.findViewById(R.id.player_next_button)
private var bufferingIndicator: ProgressBar = rootView.findViewById(R.id.player_buffering_indicator) private var bufferingIndicator: ProgressBar = rootView.findViewById(R.id.player_buffering_indicator)
private var sheetStreamingLinkHeadline: TextView = rootView.findViewById(R.id.sheet_streaming_link_headline) private var sheetStreamingLinkHeadline: TextView? = rootView.findViewById(R.id.sheet_streaming_link_headline)
private var sheetStreamingLinkView: TextView = rootView.findViewById(R.id.sheet_streaming_link) private var sheetStreamingLinkView: TextView? = rootView.findViewById(R.id.sheet_streaming_link)
private var sheetMetadataHistoryHeadline: TextView = rootView.findViewById(R.id.sheet_metadata_headline) private var sheetMetadataHistoryHeadline: TextView? = rootView.findViewById(R.id.sheet_metadata_headline)
private var sheetMetadataHistoryView: TextView = rootView.findViewById(R.id.sheet_metadata_history) private var sheetMetadataHistoryView: TextView? = rootView.findViewById(R.id.sheet_metadata_history)
private var sheetNextMetadataView: ImageButton = rootView.findViewById(R.id.sheet_next_metadata_button) private var sheetNextMetadataView: ImageButton? = rootView.findViewById(R.id.sheet_next_metadata_button)
private var sheetPreviousMetadataView: ImageButton = rootView.findViewById(R.id.sheet_previous_metadata_button) private var sheetPreviousMetadataView: ImageButton? = rootView.findViewById(R.id.sheet_previous_metadata_button)
private var sheetCopyMetadataButtonView: ImageButton = rootView.findViewById(R.id.copy_station_metadata_button) private var sheetCopyMetadataButtonView: ImageButton? = rootView.findViewById(R.id.copy_station_metadata_button)
private var sheetShareLinkButtonView: ImageView = rootView.findViewById(R.id.sheet_share_link_button) private var mediaRouteButton: MediaRouteButton? = rootView.findViewById(R.id.media_route_button)
private var sheetBitrateView: TextView = rootView.findViewById(R.id.sheet_bitrate_view) private var sheetShareLinkButtonView: ImageView? = rootView.findViewById(R.id.sheet_share_link_button)
var sheetSleepTimerStartButtonView: ImageButton = rootView.findViewById(R.id.sleep_timer_start_button) private var sheetBitrateView: TextView? = rootView.findViewById(R.id.sheet_bitrate_view)
var sheetSleepTimerCancelButtonView: ImageButton = rootView.findViewById(R.id.sleep_timer_cancel_button) var sheetSleepTimerStartButtonView: ImageButton? = rootView.findViewById(R.id.sleep_timer_start_button)
var sheetSleepTimerCancelButtonView: ImageButton? = rootView.findViewById(R.id.sleep_timer_cancel_button)
private var sheetSleepTimerRemainingTimeView: TextView = rootView.findViewById(R.id.sleep_timer_remaining_time) private var sheetSleepTimerRemainingTimeView: TextView = rootView.findViewById(R.id.sleep_timer_remaining_time)
private var onboardingLayout: ConstraintLayout = rootView.findViewById(R.id.onboarding_layout) private var onboardingLayout: ConstraintLayout = rootView.findViewById(R.id.onboarding_layout)
private var bottomSheetBehavior: BottomSheetBehavior<ConstraintLayout> = BottomSheetBehavior.from(bottomSheet) private var bottomSheetBehavior: BottomSheetBehavior<ConstraintLayout>? = bottomSheet?.let { BottomSheetBehavior.from(it) }
private var metadataHistory: MutableList<String> private var metadataHistory: MutableList<String>
private var metadataHistoryPosition: Int private var metadataHistoryPosition: Int
private var isBuffering: Boolean private var isBuffering: Boolean
@@ -96,80 +89,91 @@ data class LayoutHolder(var rootView: View) {
recyclerView.itemAnimator = DefaultItemAnimator() recyclerView.itemAnimator = DefaultItemAnimator()
// set up metadata history next and previous buttons // set up metadata history next and previous buttons
sheetPreviousMetadataView.setOnClickListener { sheetPreviousMetadataView?.setOnClickListener {
if (metadataHistory.isNotEmpty()) { if (metadataHistory.isNotEmpty()) {
if (metadataHistoryPosition > 0) { if (metadataHistoryPosition > 0) {
metadataHistoryPosition -= 1 metadataHistoryPosition -= 1
} else { } else {
metadataHistoryPosition = metadataHistory.size - 1 metadataHistoryPosition = metadataHistory.size - 1
} }
sheetMetadataHistoryView.text = metadataHistory[metadataHistoryPosition] sheetMetadataHistoryView?.text = metadataHistory[metadataHistoryPosition]
} }
} }
sheetNextMetadataView.setOnClickListener { sheetNextMetadataView?.setOnClickListener {
if (metadataHistory.isNotEmpty()) { if (metadataHistory.isNotEmpty()) {
if (metadataHistoryPosition < metadataHistory.size - 1) { if (metadataHistoryPosition < metadataHistory.size - 1) {
metadataHistoryPosition += 1 metadataHistoryPosition += 1
} else { } else {
metadataHistoryPosition = 0 metadataHistoryPosition = 0
} }
sheetMetadataHistoryView.text = metadataHistory[metadataHistoryPosition] sheetMetadataHistoryView?.text = metadataHistory[metadataHistoryPosition]
} }
} }
sheetMetadataHistoryView.setOnLongClickListener { sheetMetadataHistoryView?.setOnLongClickListener {
copyMetadataHistoryToClipboard() copyMetadataHistoryToClipboard()
return@setOnLongClickListener true return@setOnLongClickListener true
} }
sheetMetadataHistoryHeadline.setOnLongClickListener { sheetMetadataHistoryHeadline?.setOnLongClickListener {
copyMetadataHistoryToClipboard() copyMetadataHistoryToClipboard()
return@setOnLongClickListener true return@setOnLongClickListener true
} }
// Set up MediaRouteButton (Google Cast)
mediaRouteButton?.let {
CastButtonFactory.setUpMediaRouteButton(rootView.context, it)
}
// set layout for player // set layout for player
setupBottomSheet() setupBottomSheet()
} }
/* Updates the player views */ /* Updates the player views */
@SuppressLint("DefaultLocale")
fun updatePlayerViews(context: Context, station: Station, isPlaying: Boolean) { fun updatePlayerViews(context: Context, station: Station, isPlaying: Boolean) {
// set default metadata views, when playback has stopped
if (!isPlaying) { if (!isPlaying) {
metadataView.text = station.name metadataView?.text = station.name
sheetMetadataHistoryView.text = station.name sheetMetadataHistoryView?.text = station.name
// sheetMetadataHistoryView.isSelected = true
} }
// update name // update name
stationNameView.text = station.name stationNameView?.text = station.name
// toggle text scrolling (marquee) if necessary // toggle text scrolling (marquee) if necessary
stationNameView.isSelected = isPlaying stationNameView?.isSelected = isPlaying
// reduce the shadow left and right because of scrolling (Marquee) // reduce the shadow left and right because of scrolling (Marquee)
stationNameView.setFadingEdgeLength(8) stationNameView?.setFadingEdgeLength(8)
// update cover // update cover
if (station.imageColor != -1) { if (station.imageColor != -1) {
stationImageView.setBackgroundColor(station.imageColor) stationImageView?.setBackgroundColor(station.imageColor)
} }
stationImageView.setImageBitmap(ImageHelper.getStationImage(context, station.smallImage)) stationImageView?.setImageBitmap(ImageHelper.getStationImage(context, station.smallImage))
stationImageView.contentDescription = "${context.getString(R.string.descr_player_station_image)}: ${station.name}" stationImageView?.contentDescription = "${context.getString(R.string.descr_player_station_image)}: ${station.name}"
// update streaming link // update streaming link
sheetStreamingLinkView.text = station.getStreamUri() sheetStreamingLinkView?.text = station.getStreamUri()
val bitrateText: CharSequence = if (station.codec.isNotEmpty()) { val bitrateText: CharSequence = if (station.codec.isNotEmpty()) {
if (station.bitrate == 0) { if (station.bitrate == 0) {
// show only the codec when the bitrate is at "0" from radio-browser.info API // show only the codec when the bitrate is at "0" from radio-browser.info API
station.codec station.codec
} else { } else {
val kiloBytesPerSecond = station.bitrate / 8F
val dataRateString = if (kiloBytesPerSecond >= 1000) {
String.format("%.2f mb/s", kiloBytesPerSecond / 1000F)
} else {
String.format("%.0f kb/s", kiloBytesPerSecond)
}
// show the bitrate and codec if the result is available in the radio-browser.info API // show the bitrate and codec if the result is available in the radio-browser.info API
buildString { buildString {
append(station.codec) append(station.codec)
append(" | ") append(" | ")
append(station.bitrate) append(station.bitrate)
append("kbps") append("kbps")
append(" | ")
append(dataRateString)
} }
} }
} else { } else {
@@ -178,50 +182,50 @@ data class LayoutHolder(var rootView: View) {
} }
// update bitrate // update bitrate
sheetBitrateView.text = bitrateText sheetBitrateView?.text = bitrateText
// update click listeners // update click listeners
sheetStreamingLinkHeadline.setOnClickListener { sheetStreamingLinkHeadline?.setOnClickListener {
copyToClipboard( copyToClipboard(
context, context,
sheetStreamingLinkView.text sheetStreamingLinkView?.text ?: ""
) )
} }
sheetStreamingLinkView.setOnClickListener { sheetStreamingLinkView?.setOnClickListener {
copyToClipboard( copyToClipboard(
context, context,
sheetStreamingLinkView.text sheetStreamingLinkView?.text ?: ""
) )
} }
sheetMetadataHistoryHeadline.setOnClickListener { sheetMetadataHistoryHeadline?.setOnClickListener {
copyToClipboard( copyToClipboard(
context, context,
sheetMetadataHistoryView.text sheetMetadataHistoryView?.text ?: ""
) )
} }
sheetMetadataHistoryView.setOnClickListener { sheetMetadataHistoryView?.setOnClickListener {
copyToClipboard( copyToClipboard(
context, context,
sheetMetadataHistoryView.text sheetMetadataHistoryView?.text ?: ""
) )
} }
sheetCopyMetadataButtonView.setOnClickListener { sheetCopyMetadataButtonView?.setOnClickListener {
copyToClipboard( copyToClipboard(
context, context,
sheetMetadataHistoryView.text sheetMetadataHistoryView?.text ?: ""
) )
} }
sheetBitrateView.setOnClickListener { sheetBitrateView?.setOnClickListener {
copyToClipboard( copyToClipboard(
context, context,
sheetBitrateView.text sheetBitrateView?.text ?: ""
) )
} }
sheetShareLinkButtonView.setOnClickListener { sheetShareLinkButtonView?.setOnClickListener {
val share = Intent.createChooser(Intent().apply { val share = Intent.createChooser(Intent().apply {
action = Intent.ACTION_SEND action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TITLE, stationNameView.text) putExtra(Intent.EXTRA_TITLE, stationNameView?.text)
putExtra(Intent.EXTRA_TEXT, sheetStreamingLinkView.text) putExtra(Intent.EXTRA_TEXT, sheetStreamingLinkView?.text ?: "")
type = "text/plain" type = "text/plain"
}, null) }, null)
context.startActivity(share) context.startActivity(share)
@@ -254,11 +258,11 @@ data class LayoutHolder(var rootView: View) {
fun updateMetadata(metadataHistoryList: MutableList<String>?) { fun updateMetadata(metadataHistoryList: MutableList<String>?) {
if (!metadataHistoryList.isNullOrEmpty()) { if (!metadataHistoryList.isNullOrEmpty()) {
metadataHistory = metadataHistoryList metadataHistory = metadataHistoryList
if (metadataHistory.last() != metadataView.text) { if (metadataHistory.last() != metadataView?.text) {
metadataHistoryPosition = metadataHistory.size - 1 metadataHistoryPosition = metadataHistory.size - 1
val metadataString = metadataHistory[metadataHistoryPosition] val metadataString = metadataHistory[metadataHistoryPosition]
metadataView.text = metadataString metadataView?.text = metadataString
sheetMetadataHistoryView.text = metadataString sheetMetadataHistoryView?.text = metadataString
} }
} }
} }
@@ -268,14 +272,16 @@ data class LayoutHolder(var rootView: View) {
fun updateSleepTimer(context: Context, timeRemaining: Long = 0L) { fun updateSleepTimer(context: Context, timeRemaining: Long = 0L) {
when (timeRemaining) { when (timeRemaining) {
0L -> { 0L -> {
sleepTimerRunningViews.isGone = true sleepTimerRunningViews?.isGone = true
sheetSleepTimerRemainingTimeView.isVisible = false
} }
else -> { else -> {
sleepTimerRunningViews.isVisible = true sleepTimerRunningViews?.isVisible = true
sheetSleepTimerRemainingTimeView.isVisible = true
val sleepTimerTimeRemaining = DateTimeHelper.convertToHoursMinutesSeconds(timeRemaining) val sleepTimerTimeRemaining = DateTimeHelper.convertToHoursMinutesSeconds(timeRemaining)
sheetSleepTimerRemainingTimeView.text = sleepTimerTimeRemaining sheetSleepTimerRemainingTimeView.text = sleepTimerTimeRemaining
sheetSleepTimerRemainingTimeView.contentDescription = "${context.getString(R.string.descr_expanded_player_sleep_timer_remaining_time)}: $sleepTimerTimeRemaining" sheetSleepTimerRemainingTimeView.contentDescription = "${context.getString(R.string.descr_expanded_player_sleep_timer_remaining_time)}: $sleepTimerTimeRemaining"
stationNameView.isSelected = false stationNameView?.isSelected = false
} }
} }
} }
@@ -287,12 +293,10 @@ data class LayoutHolder(var rootView: View) {
playButtonView.setImageResource(R.drawable.ic_audio_waves_animated) playButtonView.setImageResource(R.drawable.ic_audio_waves_animated)
val animatedVectorDrawable = playButtonView.drawable as? AnimatedVectorDrawable val animatedVectorDrawable = playButtonView.drawable as? AnimatedVectorDrawable
animatedVectorDrawable?.start() animatedVectorDrawable?.start()
sheetSleepTimerStartButtonView.isVisible = true sheetSleepTimerStartButtonView?.isVisible = true
// bufferingIndicator.isVisible = false
} else { } else {
playButtonView.setImageResource(R.drawable.ic_player_play_symbol_42dp) playButtonView.setImageResource(R.drawable.ic_player_play_symbol_42dp)
sheetSleepTimerStartButtonView.isVisible = false sheetSleepTimerStartButtonView?.isVisible = false
// bufferingIndicator.isVisible = isBuffering
} }
} }
@@ -303,23 +307,11 @@ data class LayoutHolder(var rootView: View) {
isBuffering = buffering isBuffering = buffering
} }
/* Toggles visibility of player depending on playback state - hiding it when playback is stopped (not paused or playing) */
// fun togglePlayerVisibility(context: Context, playbackState: Int): Boolean {
// when (playbackState) {
// PlaybackStateCompat.STATE_STOPPED -> return hidePlayer(context)
// PlaybackStateCompat.STATE_NONE -> return hidePlayer(context)
// PlaybackStateCompat.STATE_ERROR -> return hidePlayer(context)
// else -> return showPlayer(context)
// }
// }
/* Toggles visibility of the download progress indicator */ /* Toggles visibility of the download progress indicator */
fun toggleDownloadProgressIndicator() { fun toggleDownloadProgressIndicator() {
when (PreferencesHelper.loadActiveDownloads()) { when (PreferencesHelper.loadActiveDownloads()) {
Keys.ACTIVE_DOWNLOADS_EMPTY -> downloadProgressIndicator.isGone = true Keys.ACTIVE_DOWNLOADS_EMPTY -> downloadProgressIndicator?.isGone = true
else -> downloadProgressIndicator.isVisible = true else -> downloadProgressIndicator?.isVisible = true
} }
} }
@@ -340,27 +332,27 @@ data class LayoutHolder(var rootView: View) {
/* Initiates the rotation animation of the play button */ /* Initiates the rotation animation of the play button */
fun animatePlaybackButtonStateTransition(context: Context, isPlaying: Boolean) { fun animatePlaybackButtonStateTransition(context: Context, isPlaying: Boolean) {
when (isPlaying) { if (context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
true -> { // TV: Toggle play button immediately for snappier feel
val rotateClockwise = AnimationUtils.loadAnimation(context, R.anim.rotate_clockwise_slow) togglePlayButton(isPlaying)
rotateClockwise.setAnimationListener(createAnimationListener(true)) } else {
playButtonView.startAnimation(rotateClockwise) // Handy/Tablet: Rotate the play button
} val rotateAnimation = AnimationUtils.loadAnimation(context, if (isPlaying) R.anim.rotate_clockwise_slow else R.anim.rotate_counterclockwise_fast)
false -> { rotateAnimation.setAnimationListener(createAnimationListener(isPlaying))
val rotateCounterClockwise = AnimationUtils.loadAnimation(context, R.anim.rotate_counterclockwise_fast) playButtonView.startAnimation(rotateAnimation)
rotateCounterClockwise.setAnimationListener(createAnimationListener(false))
playButtonView.startAnimation(rotateCounterClockwise)
}
} }
} }
/* Shows player */ /* Shows player */
fun showPlayer(context: Context): Boolean { fun showPlayer(context: Context): Boolean {
if (bottomSheetBehavior != null) {
UiHelper.setViewMargins(context, recyclerView, 0, 0, 0, Keys.BOTTOM_SHEET_PEEK_HEIGHT) UiHelper.setViewMargins(context, recyclerView, 0, 0, 0, Keys.BOTTOM_SHEET_PEEK_HEIGHT)
if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_HIDDEN && onboardingLayout.visibility == View.GONE) { if (bottomSheetBehavior?.state == BottomSheetBehavior.STATE_HIDDEN && onboardingLayout.isGone) {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
} else {
UiHelper.setViewMargins(context, recyclerView, 0, 0, 0, 0)
} }
return true return true
} }
@@ -369,15 +361,15 @@ data class LayoutHolder(var rootView: View) {
/* Hides player */ /* Hides player */
private fun hidePlayer(context: Context): Boolean { private fun hidePlayer(context: Context): Boolean {
UiHelper.setViewMargins(context, recyclerView, 0, 0, 0, 0) UiHelper.setViewMargins(context, recyclerView, 0, 0, 0, 0)
bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN
return true return true
} }
/* Minimizes player sheet if expanded */ /* Minimizes player sheet if expanded */
fun minimizePlayerIfExpanded(): Boolean { fun minimizePlayerIfExpanded(): Boolean {
return if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) { return if (bottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
true true
} else { } else {
false false
@@ -390,7 +382,7 @@ data class LayoutHolder(var rootView: View) {
return object : Animation.AnimationListener { return object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {} override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) { override fun onAnimationEnd(animation: Animation) {
// set up button symbol and playback indicator afterwards // set up button symbol and playback indicator afterward
togglePlayButton(isPlaying) togglePlayButton(isPlaying)
} }
@@ -401,9 +393,10 @@ data class LayoutHolder(var rootView: View) {
/* Sets up the player (BottomSheet) */ /* Sets up the player (BottomSheet) */
private fun setupBottomSheet() { private fun setupBottomSheet() {
if (bottomSheetBehavior != null) {
// show / hide the small player // show / hide the small player
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
bottomSheetBehavior.addBottomSheetCallback(object : bottomSheetBehavior?.addBottomSheetCallback(object :
BottomSheetBehavior.BottomSheetCallback() { BottomSheetBehavior.BottomSheetCallback() {
override fun onSlide(view: View, slideOffset: Float) { override fun onSlide(view: View, slideOffset: Float) {
} }
@@ -420,19 +413,20 @@ data class LayoutHolder(var rootView: View) {
} }
}) })
// toggle collapsed state on tap // toggle collapsed state on tap
bottomSheet.setOnClickListener { toggleBottomSheetState() } bottomSheet?.setOnClickListener { toggleBottomSheetState() }
stationImageView.setOnClickListener { toggleBottomSheetState() } stationImageView?.setOnClickListener { toggleBottomSheetState() }
stationNameView.setOnClickListener { toggleBottomSheetState() } stationNameView?.setOnClickListener { toggleBottomSheetState() }
metadataView.setOnClickListener { toggleBottomSheetState() } metadataView?.setOnClickListener { toggleBottomSheetState() }
}
} }
/* Toggle expanded/collapsed state of bottom sheet */ /* Toggle expanded/collapsed state of bottom sheet */
private fun toggleBottomSheetState() { private fun toggleBottomSheetState() {
when (bottomSheetBehavior.state) { when (bottomSheetBehavior?.state) {
BottomSheetBehavior.STATE_COLLAPSED -> bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED -> bottomSheetBehavior?.state =
BottomSheetBehavior.STATE_EXPANDED BottomSheetBehavior.STATE_EXPANDED
else -> bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED else -> bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
} }
} }
@@ -440,7 +434,7 @@ data class LayoutHolder(var rootView: View) {
/* /*
* Inner class: Custom LinearLayoutManager * Inner class: Custom LinearLayoutManager
*/ */
private inner class CustomLayoutManager(context: Context) : private class CustomLayoutManager(context: Context) :
LinearLayoutManager(context, VERTICAL, false) { LinearLayoutManager(context, VERTICAL, false) {
override fun supportsPredictiveItemAnimations(): Boolean { override fun supportsPredictiveItemAnimations(): Boolean {
return true return true
@@ -1,17 +1,3 @@
/*
* PlayerState.kt
* Implements the PlayerState class
* A PlayerState holds parameters describing the state of the player part of the UI
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package com.michatec.radio.ui package com.michatec.radio.ui
import android.os.Parcelable import android.os.Parcelable
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/list_card_stroke_focused" android:state_focused="true" />
<item android:color="@color/list_card_stroke_background" />
</selector>
@@ -1,9 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="@color/icon_default"
android:pathData="m11.999,2.623c-5.54,0 -9.999,4.462 -9.999,10.001 -0,1.878 0.529,3.721 1.528,5.313l8.336,-10.778c0.06,-0.077 0.209,-0.077 0.27,0l3.482,4.502h-2.494l0.054,0.199h2.594l0.736,0.949h-3.062l0.086,0.311h3.217l0.647,0.836h-3.631l0.113,0.402h3.827l0.579,0.745h-4.198l0.137,0.49h4.438l0.508,0.655h-4.764l0.152,0.542h5.031l0.468,0.606h-5.33l0.152,0.542h5.598c0.998,-1.592 1.528,-3.435 1.528,-5.313 0,-5.54 -4.462,-10.001 -10.001,-10.001zM15.044,18.543 L15.196,19.085h4.438c0.145,-0.171 0.294,-0.361 0.428,-0.542zM15.365,19.69 L15.515,20.232h2.969c0.194,-0.166 0.405,-0.357 0.594,-0.542zM15.684,20.838 L15.836,21.377h1.003c0.296,-0.17 0.571,-0.343 0.868,-0.539z" />
</vector>
@@ -0,0 +1,17 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/icon_default"
android:pathData="M17.65,6.35C16.2,4.9 14.21,4 12,4
7.58,4 4,7.58 4,12h2
c0,-3.31 2.69,-6 6,-6
1.66,0 3.14,0.69 4.22,1.78L13,11h7V4l-2.35,2.35z
M6.35,17.65C7.8,19.1 9.79,20 12,20
c4.42,0 8,-3.58 8,-8h-2
c0,3.31 -2.69,6 -6,6
-1.66,0 -3.14,-0.69 -4.22,-1.78L11,13H4v7l2.35,-2.35z"/>
</vector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/search_result_background_selected" android:state_focused="true" />
<item android:drawable="@android:color/transparent" />
</selector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/list_card_stroke_focused" android:state_focused="true" />
<item android:color="@color/list_card_stroke_background" />
</selector>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape android:shape="rectangle">
<solid android:color="#80FFFFFF" />
<corners android:radius="8dp" />
<stroke android:width="3dp" android:color="@color/default_neutral_white" />
</shape>
</item>
<item android:drawable="@android:color/transparent" />
</selector>
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- View is "selected" --> <!-- View is "selected" or "focused" (for TV) -->
<item android:drawable="@drawable/shape_search_result_item_selected" android:state_selected="true" /> <item android:drawable="@drawable/shape_search_result_item_selected" android:state_selected="true" />
<item android:drawable="@drawable/shape_search_result_item_selected" android:state_focused="true" />
<!-- Default state. --> <!-- Default state. -->
<item android:drawable="@drawable/shape_search_result_item" /> <item android:drawable="@drawable/shape_search_result_item" />
@@ -1,8 +1,8 @@
<shape xmlns:android="http://schemas.android.com/apk/res/android" <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"> android:shape="oval">
<stroke <stroke
android:width="2dp" android:width="4dp"
android:color="@color/default_neutral_lighter" /> android:color="@color/default_neutral_white" />
<size <size
android:width="56dp" android:width="56dp"
android:height="56dp" /> android:height="56dp" />
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splashBackgroundColor" />
<item
android:width="160dp"
android:height="160dp"
android:gravity="center"
android:drawable="@mipmap/ic_launcher" />
</layer-list>
@@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_player_sheet_background"
android:padding="24dp">
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/station_icon"
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@drawable/shape_cover_small"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shapeAppearanceOverlay="@style/RoundedCorners"
app:srcCompat="@drawable/ic_default_station_image_72dp" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/player_station_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:textAppearance="@style/TextAppearance.Material3.HeadlineMedium"
android:textColor="@color/player_sheet_text_main"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="@+id/player_play_button"
app:layout_constraintStart_toEndOf="@+id/station_icon"
app:layout_constraintTop_toTopOf="@+id/station_icon"
tools:text="Station Name" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/player_station_metadata"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:textColor="@color/player_sheet_text_main"
app:layout_constraintEnd_toEndOf="@+id/player_station_name"
app:layout_constraintStart_toStartOf="@+id/player_station_name"
app:layout_constraintTop_toBottomOf="@+id/player_station_name"
tools:text="Metadata Info" />
<ImageButton
android:id="@+id/player_play_button"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="@drawable/selector_play_button"
android:focusable="true"
android:scaleType="center"
app:layout_constraintBottom_toBottomOf="@+id/station_icon"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/station_icon"
app:srcCompat="@drawable/ic_player_play_symbol_42dp" />
<LinearLayout
android:id="@+id/detailed_controls_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:gravity="center_vertical"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="@+id/station_icon">
<ImageButton
android:id="@+id/sheet_previous_metadata_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
app:srcCompat="@drawable/ic_chevron_left_24dp" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/sheet_metadata_history"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginHorizontal="16dp"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.Material3.BodyMedium"
android:textColor="@color/player_sheet_text_main"
tools:text="Metadata History" />
<ImageButton
android:id="@+id/sheet_next_metadata_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
app:srcCompat="@drawable/ic_chevron_right_24dp" />
<ImageButton
android:id="@+id/copy_station_metadata_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="16dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
app:srcCompat="@drawable/ic_copy_content_24dp" />
<ImageButton
android:id="@+id/sleep_timer_start_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="16dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
app:srcCompat="@drawable/ic_sleep_timer_24dp" />
<ImageButton
android:id="@+id/sleep_timer_cancel_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="8dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
android:visibility="gone"
app:srcCompat="@drawable/ic_clear_24dp" />
</LinearLayout>
<com.google.android.material.textview.MaterialTextView
android:id="@+id/sleep_timer_remaining_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textAppearance="@style/TextAppearance.Material3.LabelLarge"
android:textColor="@color/player_sheet_text_main"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/detailed_controls_row"
tools:text="15:00" />
</androidx.constraintlayout.widget.ConstraintLayout>
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/station_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:clipToPadding="false"
android:paddingBottom="16dp"
android:nextFocusRight="@id/dialog_negative_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.7" />
<LinearLayout
android:id="@+id/dialog_button_container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/guideline"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="@+id/dialog_positive_button"
style="@style/Widget.Material3.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nextFocusLeft="@id/station_list"
android:text="@string/dialog_find_station_button_add" />
<Button
android:id="@+id/dialog_negative_button"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:nextFocusLeft="@id/station_list"
android:text="@string/dialog_generic_button_cancel" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<androidx.appcompat.widget.SearchView
android:id="@+id/station_search_box_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:nextFocusRight="@id/dialog_negative_button"
android:nextFocusDown="@id/station_search_result_list"
app:iconifiedByDefault="false"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:queryHint="@string/dialog_find_station_hint" />
<ProgressBar
android:id="@+id/search_request_progress_indicator"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:indeterminate="true"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="@+id/station_search_box_view"
app:layout_constraintStart_toStartOf="@+id/station_search_box_view"
app:layout_constraintTop_toBottomOf="@+id/station_search_box_view" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/no_results_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dialog_find_station_no_results"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:visibility="gone"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/search_request_progress_indicator" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/station_search_result_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:clipToPadding="false"
android:paddingBottom="16dp"
android:nextFocusRight="@id/dialog_negative_button"
android:nextFocusUp="@id/station_search_box_view"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/no_results_text_view" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.7" />
<!-- Right side: Actions -->
<LinearLayout
android:id="@+id/dialog_button_container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/guideline"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="@+id/dialog_positive_button"
style="@style/Widget.Material3.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nextFocusUp="@id/station_search_box_view"
android:nextFocusLeft="@id/station_search_result_list"
android:text="@string/dialog_find_station_button_add" />
<Button
android:id="@+id/dialog_negative_button"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:nextFocusLeft="@id/station_search_result_list"
android:text="@string/dialog_generic_button_cancel" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="800dp"
android:layout_height="wrap_content"
android:padding="24dp">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/dialog_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/dialog_error_message_default"
android:textAppearance="@style/TextAppearance.Material3.HeadlineSmall"
android:textColor="@color/text_default"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="@string/dialog_error_message_default" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/dialog_details_link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:focusable="true"
android:clickable="true"
android:background="?attr/selectableItemBackground"
android:padding="8dp"
android:text="@string/dialog_generic_details_button"
android:textAppearance="@style/TextAppearance.Material3.LabelLarge"
android:textColor="@color/text_default"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dialog_message"
tools:text="@string/dialog_generic_details_button" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/dialog_details"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:focusable="true"
android:clickable="true"
android:scrollbars="vertical"
android:text="@string/dialog_opml_import_details_default"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:textColor="@color/text_default"
android:textIsSelectable="true"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dialog_details_link"
tools:text="@string/dialog_opml_import_details_default" />
</androidx.constraintlayout.widget.ConstraintLayout>
@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_selection_title"
android:textSize="24sp"
android:textStyle="bold"
android:paddingBottom="16dp" />
<RadioGroup
android:id="@+id/preset_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_preset_none"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_none"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
<RadioButton
android:id="@+id/radio_preset_rock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_rock"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
<RadioButton
android:id="@+id/radio_preset_pop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_pop"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
<RadioButton
android:id="@+id/radio_preset_jazz"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_jazz"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
<RadioButton
android:id="@+id/radio_preset_flat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_flat"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
</RadioGroup>
</LinearLayout>
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_title"
android:textSize="24sp"
android:textStyle="bold"
android:paddingBottom="16dp" />
<RadioGroup
android:id="@+id/theme_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_theme_follow_system"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_mode_device_default"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
<RadioButton
android:id="@+id/radio_theme_light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_mode_light"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
<RadioButton
android:id="@+id/radio_theme_dark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_mode_dark"
android:textSize="20sp"
android:padding="12dp"
android:focusable="true"
android:clickable="true" />
</RadioGroup>
</LinearLayout>
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:focusable="true"
android:clickable="true"
android:nextFocusRight="@+id/dialog_negative_button"
android:background="@drawable/selector_search_result_item">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/station_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:textAppearance="@style/TextAppearance.Material3.TitleLarge"
android:textColor="@color/text_default"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Station Name" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/station_url"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:textColor="@color/text_lightweight"
app:layout_constraintEnd_toEndOf="@+id/station_name"
app:layout_constraintStart_toStartOf="@+id/station_name"
app:layout_constraintTop_toBottomOf="@+id/station_name"
tools:text="http://stream.url" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/station_bitrate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:singleLine="true"
android:textAppearance="@style/TextAppearance.Material3.LabelLarge"
android:textColor="@color/text_lightweight"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/station_url"
app:layout_constraintStart_toStartOf="@+id/station_url"
app:layout_constraintTop_toBottomOf="@+id/station_url"
tools:text="128 kbps" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
@@ -0,0 +1,206 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/station_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:clipToPadding="false"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
layout="@layout/element_onboarding"
android:visibility="gone" />
</androidx.constraintlayout.widget.ConstraintLayout>
<ScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2"
android:background="@color/player_sheet_background"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/player_ui"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="24dp">
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/station_icon"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_marginTop="16dp"
android:background="@drawable/shape_cover_small"
android:contentDescription="@string/descr_player_station_image"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shapeAppearanceOverlay="@style/RoundedCorners"
app:srcCompat="@drawable/ic_default_station_image_72dp" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/player_station_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.Material3.HeadlineMedium"
android:textColor="@color/player_sheet_text_main"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/station_icon"
tools:text="Station Name" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/player_station_metadata"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:ellipsize="end"
android:singleLine="true"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:textColor="@color/player_sheet_text_main"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/player_station_name"
tools:text="Artist - Title" />
<LinearLayout
android:id="@+id/controls_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/player_station_metadata">
<ImageButton
android:id="@+id/player_prev_button"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginEnd="16dp"
android:background="@drawable/selector_generic_button_focus"
android:contentDescription="@string/descr_expanded_player_metadata_previous_button"
android:focusable="true"
android:padding="12dp"
app:srcCompat="@drawable/ic_chevron_left_24dp" />
<ImageButton
android:id="@+id/player_play_button"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="@drawable/selector_play_button"
android:contentDescription="@string/descr_player_playback_button"
android:focusable="true"
android:scaleType="center"
app:srcCompat="@drawable/ic_player_play_symbol_42dp" />
<ImageButton
android:id="@+id/player_next_button"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="16dp"
android:background="@drawable/selector_generic_button_focus"
android:contentDescription="@string/descr_expanded_player_metadata_next_button"
android:focusable="true"
android:padding="12dp"
app:srcCompat="@drawable/ic_chevron_right_24dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/secondary_controls_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/controls_row">
<ImageButton
android:id="@+id/copy_station_metadata_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginEnd="12dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
android:padding="8dp"
app:srcCompat="@drawable/ic_copy_content_24dp"
tools:ignore="ContentDescription" />
<ImageButton
android:id="@+id/sleep_timer_start_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginEnd="12dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
android:padding="8dp"
app:srcCompat="@drawable/ic_sleep_timer_24dp"
tools:ignore="ContentDescription" />
<ImageButton
android:id="@+id/sleep_timer_cancel_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="@drawable/selector_generic_button_focus"
android:focusable="true"
android:padding="8dp"
android:visibility="gone"
app:srcCompat="@drawable/ic_clear_24dp"
tools:ignore="ContentDescription" />
</LinearLayout>
<ProgressBar
android:id="@+id/player_buffering_indicator"
style="?android:attr/progressBarStyleLarge"
android:layout_width="96dp"
android:layout_height="96dp"
android:indeterminateTint="@color/player_button_buffering"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="@+id/controls_row"
app:layout_constraintEnd_toEndOf="@+id/controls_row"
app:layout_constraintStart_toStartOf="@+id/controls_row"
app:layout_constraintTop_toTopOf="@+id/controls_row" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/sleep_timer_remaining_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textAppearance="@style/TextAppearance.Material3.BodyMedium"
android:textColor="@color/player_sheet_text_main"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/secondary_controls_row"
tools:text="15:00" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</LinearLayout>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/visualizer_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"
android:focusable="true" />
</LinearLayout>
+47
View File
@@ -4,6 +4,8 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="?android:attr/colorBackground"
android:fitsSystemWindows="true"
tools:context=".MainActivity"> tools:context=".MainActivity">
<com.google.android.material.appbar.MaterialToolbar <com.google.android.material.appbar.MaterialToolbar
@@ -28,4 +30,49 @@
app:layout_constraintTop_toBottomOf="@+id/main_toolbar" app:layout_constraintTop_toBottomOf="@+id/main_toolbar"
app:navGraph="@navigation/nav_graph_main" /> app:navGraph="@navigation/nav_graph_main" />
<!-- SPLASH / LOADING SCREEN -->
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/loading_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/splashBackgroundColor"
android:elevation="10dp"
android:visibility="visible">
<ImageView
android:id="@+id/loading_logo"
android:layout_width="160dp"
android:layout_height="160dp"
android:contentDescription="@string/icon_launcher"
android:src="@mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="@string/loading"
android:textAppearance="@style/TextAppearance.Material3.HeadlineSmall"
android:textColor="@color/default_neutral_white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/loading_logo" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:indeterminate="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/loading_logo"
android:visibility="invisible" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
@@ -211,6 +211,18 @@
app:layout_constraintTop_toBottomOf="@+id/sheet_previous_metadata_button" app:layout_constraintTop_toBottomOf="@+id/sheet_previous_metadata_button"
app:srcCompat="@drawable/ic_copy_content_24dp" /> app:srcCompat="@drawable/ic_copy_content_24dp" />
<androidx.mediarouter.app.MediaRouteButton
android:id="@+id/media_route_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="@+id/copy_station_metadata_button"
app:layout_constraintStart_toEndOf="@+id/copy_station_metadata_button"
app:layout_constraintTop_toTopOf="@+id/copy_station_metadata_button"
app:mediaRouteButtonTint="@color/player_sheet_text_main" />
<com.google.android.material.textview.MaterialTextView <com.google.android.material.textview.MaterialTextView
android:id="@+id/sheet_bitrate_view" android:id="@+id/sheet_bitrate_view"
android:layout_width="wrap_content" android:layout_width="wrap_content"
@@ -12,6 +12,8 @@
android:layout_marginStart="8dp" android:layout_marginStart="8dp"
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:layout_marginBottom="24dp" android:layout_marginBottom="24dp"
android:focusable="true"
android:clickable="true"
android:stateListAnimator="@null" android:stateListAnimator="@null"
app:backgroundTint="@color/list_card_background" app:backgroundTint="@color/list_card_background"
app:icon="@drawable/ic_add_24dp" app:icon="@drawable/ic_add_24dp"
@@ -20,6 +22,24 @@
app:strokeColor="@color/list_card_stroke_background" app:strokeColor="@color/list_card_stroke_background"
app:strokeWidth="3dp" /> app:strokeWidth="3dp" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="@+id/card_visualizer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginTop="10dp"
android:layout_marginEnd="70dp"
android:layout_marginBottom="24dp"
android:focusable="true"
android:clickable="true"
android:stateListAnimator="@null"
app:backgroundTint="@color/list_card_background"
app:icon="@drawable/ic_music_note_24dp"
app:iconTint="@color/icon_default"
app:rippleColor="@color/list_card_stroke_background"
app:strokeColor="@color/list_card_stroke_background"
app:strokeWidth="3dp" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="@+id/card_settings" android:id="@+id/card_settings"
android:layout_width="wrap_content" android:layout_width="wrap_content"
@@ -28,6 +48,8 @@
android:layout_marginTop="10dp" android:layout_marginTop="10dp"
android:layout_marginEnd="8dp" android:layout_marginEnd="8dp"
android:layout_marginBottom="24dp" android:layout_marginBottom="24dp"
android:focusable="true"
android:clickable="true"
android:stateListAnimator="@null" android:stateListAnimator="@null"
app:backgroundTint="@color/list_card_background" app:backgroundTint="@color/list_card_background"
app:icon="@drawable/ic_settings_24dp" app:icon="@drawable/ic_settings_24dp"
+30
View File
@@ -31,6 +31,21 @@
app:shapeAppearanceOverlay="@style/RoundedCorners" app:shapeAppearanceOverlay="@style/RoundedCorners"
app:srcCompat="@drawable/ic_default_station_image_72dp" /> app:srcCompat="@drawable/ic_default_station_image_72dp" />
<ProgressBar
android:id="@+id/download_progress"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="0dp"
android:layout_height="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:progressTint="@color/player_button_background"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="@+id/station_icon"
app:layout_constraintStart_toStartOf="@+id/station_icon"
app:layout_constraintTop_toTopOf="@+id/station_icon"
tools:visibility="visible" />
<com.google.android.material.imageview.ShapeableImageView <com.google.android.material.imageview.ShapeableImageView
android:id="@+id/change_image_view" android:id="@+id/change_image_view"
android:layout_width="0dp" android:layout_width="0dp"
@@ -155,6 +170,21 @@
app:layout_constraintEnd_toStartOf="@+id/save_button" app:layout_constraintEnd_toStartOf="@+id/save_button"
app:layout_constraintTop_toTopOf="@+id/save_button" /> app:layout_constraintTop_toTopOf="@+id/save_button" />
<ProgressBar
android:id="@+id/buffering_progress"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="0dp"
android:layout_height="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="4dp"
android:progressTint="@color/player_button_background"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:visibility="visible" />
<androidx.constraintlayout.widget.Group <androidx.constraintlayout.widget.Group
android:id="@+id/default_edit_views" android:id="@+id/default_edit_views"
android:layout_width="0dp" android:layout_width="0dp"
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_selection_title"
android:textSize="18sp"
android:textStyle="bold"
android:paddingBottom="12dp" />
<RadioGroup
android:id="@+id/preset_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_preset_none"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_none"
android:textSize="16sp"
android:padding="8dp"/>
<RadioButton
android:id="@+id/radio_preset_rock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_rock"
android:textSize="16sp"
android:padding="8dp"/>
<RadioButton
android:id="@+id/radio_preset_pop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_pop"
android:textSize="16sp"
android:padding="8dp"/>
<RadioButton
android:id="@+id/radio_preset_jazz"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_jazz"
android:textSize="16sp"
android:padding="8dp"/>
<RadioButton
android:id="@+id/radio_preset_flat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_preset_flat"
android:textSize="16sp"
android:padding="8dp"/>
</RadioGroup>
</LinearLayout>
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_title"
android:textSize="18sp"
android:textStyle="bold"
android:paddingBottom="12dp" />
<RadioGroup
android:id="@+id/theme_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_theme_follow_system"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_mode_device_default"
android:textSize="16sp"
android:padding="8dp"/>
<RadioButton
android:id="@+id/radio_theme_light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_mode_light"
android:textSize="16sp"
android:padding="8dp"/>
<RadioButton
android:id="@+id/radio_theme_dark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pref_theme_selection_mode_dark"
android:textSize="16sp"
android:padding="8dp"/>
</RadioGroup>
</LinearLayout>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/visualizer_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000" />
</LinearLayout>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/media_route_menu_item"
android:title="@string/media_route_menu_title"
app:actionProviderClass="androidx.mediarouter.app.MediaRouteActionProvider"
app:showAsAction="always" />
</menu>
+32 -1
View File
@@ -13,12 +13,43 @@
<action <action
android:id="@+id/action_map_fragment_to_settings_fragment" android:id="@+id/action_map_fragment_to_settings_fragment"
app:destination="@id/settings_destination" /> app:destination="@id/settings_destination" />
<action
android:id="@+id/action_map_fragment_to_visualizer_fragment"
app:destination="@id/visualizer_destination" />
<action
android:id="@+id/action_map_fragment_to_player_to_add_station"
app:destination="@id/add_station_destination" />
</fragment> </fragment>
<!-- SETTINGS --> <!-- SETTINGS -->
<fragment <fragment
android:id="@+id/settings_destination" android:id="@+id/settings_destination"
android:name="com.michatec.radio.SettingsFragment" android:name="com.michatec.radio.SettingsFragment"
android:label="Settings" /> android:label="Settings">
<action
android:id="@+id/action_settings_to_equalizer"
app:destination="@id/equalizer_destination" />
<action
android:id="@+id/action_settings_to_visualizer"
app:destination="@id/visualizer_destination" />
</fragment>
<!-- EQUALIZER -->
<fragment
android:id="@+id/equalizer_destination"
android:name="com.michatec.radio.EqualizerFragment"
android:label="Equalizer" />
<!-- VISUALIZER -->
<fragment
android:id="@+id/visualizer_destination"
android:name="com.michatec.radio.VisualizerFragment"
android:label="Visualizer" />
<!-- ADD STATION (TV) -->
<fragment
android:id="@+id/add_station_destination"
android:name="com.michatec.radio.AddStationFragment"
android:label="Add Station"
tools:layout="@layout/dialog_find_station" />
</navigation> </navigation>
+1 -1
View File
@@ -65,7 +65,7 @@
<string name="pref_edit_station_title">Rediger station</string> <string name="pref_edit_station_title">Rediger station</string>
<string name="pref_general_title">Generelt</string> <string name="pref_general_title">Generelt</string>
<string name="pref_license_title">Denne app er open source</string> <string name="pref_license_title">Denne app er open source</string>
<string name="pref_license_summary">Licenseret under MIT-licensen</string> <string name="pref_license_summary">Licenseret under GPLv3-licensen</string>
<string name="pref_links_title">Links</string> <string name="pref_links_title">Links</string>
<string name="pref_m3u_export_summary">Gem stationer som M3U-playlister til brug i andre afspillere.</string> <string name="pref_m3u_export_summary">Gem stationer som M3U-playlister til brug i andre afspillere.</string>
<string name="pref_m3u_export_title">Eksportér M3U-playliste</string> <string name="pref_m3u_export_title">Eksportér M3U-playliste</string>
+35 -1
View File
@@ -51,6 +51,10 @@
<string name="player_sheet_h2_station_metadata">Momentan läuft</string> <string name="player_sheet_h2_station_metadata">Momentan läuft</string>
<string name="player_sheet_h2_stream_url">Streaming-Adresse</string> <string name="player_sheet_h2_stream_url">Streaming-Adresse</string>
<!-- Settings --> <!-- Settings -->
<string name="pref_update_collection_title">Senderinformationnen aktualisieren</string>
<string name="pref_update_collection_summary">Die neueste Version aller Senderinformationen herunterladen.</string>
<string name="dialog_yes_no_message_update_collection">Die neueste Version aller Senderinformationen herunterladen?</string>
<string name="dialog_yes_no_positive_button_update_collection">Aktualisieren</string>
<string name="pref_advanced_title">Erweitert</string> <string name="pref_advanced_title">Erweitert</string>
<string name="pref_app_version_summary">Version</string> <string name="pref_app_version_summary">Version</string>
<string name="pref_app_version_title">App-Version</string> <string name="pref_app_version_title">App-Version</string>
@@ -66,7 +70,7 @@
<string name="pref_edit_station_title">Sender bearbeiten</string> <string name="pref_edit_station_title">Sender bearbeiten</string>
<string name="pref_general_title">Allgemein</string> <string name="pref_general_title">Allgemein</string>
<string name="pref_license_title">Diese Anwendung ist Open Source</string> <string name="pref_license_title">Diese Anwendung ist Open Source</string>
<string name="pref_license_summary">Lizenziert unter der MIT License</string> <string name="pref_license_summary">Lizenziert unter der GPLv3 License</string>
<string name="pref_links_title">Links</string> <string name="pref_links_title">Links</string>
<string name="pref_m3u_export_summary">Radiosender in einer M3U-Playlistdatei sichern, die in andere Player importiert werden können.</string> <string name="pref_m3u_export_summary">Radiosender in einer M3U-Playlistdatei sichern, die in andere Player importiert werden können.</string>
<string name="pref_m3u_export_title">M3U-Playlist exportieren</string> <string name="pref_m3u_export_title">M3U-Playlist exportieren</string>
@@ -113,4 +117,34 @@
<!-- Snackbars --> <!-- Snackbars -->
<string name="snackbar_show">Zeigen</string> <string name="snackbar_show">Zeigen</string>
<string name="snackbar_update_available">ist verfügbar!</string> <string name="snackbar_update_available">ist verfügbar!</string>
<string name="pref_audio_effects_title">Audio-Effekte</string>
<string name="pref_bass_boost_title">Bass-Boost</string>
<string name="pref_bass_boost_summary">Erhöhen Sie die Bassverstärkung.</string>
<string name="pref_reverb_title">Hall</string>
<string name="pref_reverb_summary">Reverb-Mix anpassen.</string>
<string name="pref_drc_title">Dynamikkompression</string>
<string name="pref_drc_summary">Den Dynamikbereich für eine gleichbleibende Lautstärke komprimieren.</string>
<string name="pref_eq_low_title">Equalizer: 31 Hz</string>
<string name="pref_eq_mid_title">Equalizer: 2 kHz</string>
<string name="pref_eq_high_title">Equalizer: 16 kHz</string>
<string name="pref_eq_band_1_title">Equalizer: 62 Hz</string>
<string name="pref_eq_band_2_title">Equalizer: 125 Hz</string>
<string name="pref_eq_band_3_title">Equalizer: 250 Hz</string>
<string name="pref_eq_band_4_title">Equalizer: 500 Hz</string>
<string name="pref_eq_band_5_title">Equalizer: 1 kHz</string>
<string name="pref_eq_band_6_title">Equalizer: 4 kHz</string>
<string name="pref_eq_band_7_title">Equalizer: 8 kHz</string>
<string name="pref_equalizer_title">Equalizer</string>
<string name="pref_equalizer_summary">Passen Sie die Audio-Frequenzen an.</string>
<string name="pref_equalizer_summary_off">Das Anpassen von den Audio-Frequenzen ist deaktiviert.</string>
<string name="pref_equalizer_reset_title">Equalizer zurücksetzen</string>
<string name="pref_preset_selection_title">Preset auswählen</string>
<string name="pref_preset_selection_summary">Wählen Sie ein Klangprofil</string>
<string name="pref_preset_none">Keines (Manuell)</string>
<string name="pref_preset_rock">Rock</string>
<string name="pref_preset_pop">Pop</string>
<string name="pref_preset_jazz">Jazz</string>
<string name="pref_preset_flat">Flach</string>
<string name="pref_visualizer_title">Spektrumanzeige</string>
<string name="pref_visualizer_summary">Sehe die Spektrumanzeige.</string>
</resources> </resources>
+1 -1
View File
@@ -63,7 +63,7 @@
<string name="pref_edit_station_title">Επεξεργασία Σταθμών</string> <string name="pref_edit_station_title">Επεξεργασία Σταθμών</string>
<string name="pref_general_title">Γενικές ρυθμίσεις</string> <string name="pref_general_title">Γενικές ρυθμίσεις</string>
<string name="pref_license_title">Αυτή η εφαρμογή είναι ανοικτού κώδικα</string> <string name="pref_license_title">Αυτή η εφαρμογή είναι ανοικτού κώδικα</string>
<string name="pref_license_summary">Αδειοδότηση με άδεια MIT</string> <string name="pref_license_summary">Αδειοδότηση με άδεια GPLv3</string>
<string name="pref_links_title">Σύνδεσμοι</string> <string name="pref_links_title">Σύνδεσμοι</string>
<string name="pref_m3u_export_summary">Αποθηκεύστε τους ραδιοφωνικούς σας σταθμούς σε ένα αρχείο λίστας αναπαραγωγής M3U που μπορεί να εισαχθεί σε άλλους αναπαραγωγούς.</string> <string name="pref_m3u_export_summary">Αποθηκεύστε τους ραδιοφωνικούς σας σταθμούς σε ένα αρχείο λίστας αναπαραγωγής M3U που μπορεί να εισαχθεί σε άλλους αναπαραγωγούς.</string>
<string name="pref_m3u_export_title">Εξαγωγή M3U</string> <string name="pref_m3u_export_title">Εξαγωγή M3U</string>
+1 -1
View File
@@ -65,7 +65,7 @@
<string name="pref_edit_station_title">Modifier la station</string> <string name="pref_edit_station_title">Modifier la station</string>
<string name="pref_general_title">Général</string> <string name="pref_general_title">Général</string>
<string name="pref_license_title">Cette application est Open Source</string> <string name="pref_license_title">Cette application est Open Source</string>
<string name="pref_license_summary">Sous licence MIT</string> <string name="pref_license_summary">Sous licence GPLv3</string>
<string name="pref_links_title">Liens</string> <string name="pref_links_title">Liens</string>
<string name="pref_m3u_export_summary">Enregistrez les stations dans un fichier de playlist M3U pouvant être importé dans dautres lecteurs.</string> <string name="pref_m3u_export_summary">Enregistrez les stations dans un fichier de playlist M3U pouvant être importé dans dautres lecteurs.</string>
<string name="pref_m3u_export_title">Exporter la playlist M3U</string> <string name="pref_m3u_export_title">Exporter la playlist M3U</string>
+1 -1
View File
@@ -65,7 +65,7 @@
<string name="pref_edit_station_title">局を編集</string> <string name="pref_edit_station_title">局を編集</string>
<string name="pref_general_title">一般</string> <string name="pref_general_title">一般</string>
<string name="pref_license_title">このアプリはオープンソースです</string> <string name="pref_license_title">このアプリはオープンソースです</string>
<string name="pref_license_summary">MITライセンスで提供されています</string> <string name="pref_license_summary">GPLv3ライセンスで提供されています</string>
<string name="pref_links_title">リンク</string> <string name="pref_links_title">リンク</string>
<string name="pref_m3u_export_summary">ラジオ局をM3Uプレイリストとして保存し、他のプレイヤーにインポートできます。</string> <string name="pref_m3u_export_summary">ラジオ局をM3Uプレイリストとして保存し、他のプレイヤーにインポートできます。</string>
<string name="pref_m3u_export_title">M3Uプレイリストをエクスポート</string> <string name="pref_m3u_export_title">M3Uプレイリストをエクスポート</string>
@@ -32,4 +32,5 @@
<color name="player_sheet_text_main">@android:color/system_neutral1_50</color> <color name="player_sheet_text_main">@android:color/system_neutral1_50</color>
<color name="player_sheet_icon">@android:color/system_neutral1_50</color> <color name="player_sheet_icon">@android:color/system_neutral1_50</color>
<color name="cardview_reordering">@android:color/system_accent1_100</color>
</resources> </resources>
+11 -3
View File
@@ -11,6 +11,9 @@
<item name="colorOnSurfaceVariant">@android:color/system_accent1_100</item> <item name="colorOnSurfaceVariant">@android:color/system_accent1_100</item>
<item name="android:colorBackground">@android:color/system_neutral1_900</item> <item name="android:colorBackground">@android:color/system_neutral1_900</item>
<item name="android:textColorHighlight">@android:color/system_accent1_500</item> <item name="android:textColorHighlight">@android:color/system_accent1_500</item>
<item name="colorControlHighlight">#33FFFFFF</item>
<item name="android:colorControlHighlight">#33FFFFFF</item>
<item name="android:colorFocusedHighlight">#80FFFFFF</item>
<!-- Do not use primary colored elevation overlays to present a visual hierarchy - TOO COLORFUL --> <!-- Do not use primary colored elevation overlays to present a visual hierarchy - TOO COLORFUL -->
<item name="elevationOverlayEnabled">false</item> <item name="elevationOverlayEnabled">false</item>
@@ -28,9 +31,6 @@
<!-- Don't show light status bar --> <!-- Don't show light status bar -->
<item name="android:statusBarColor">@android:color/transparent</item> <item name="android:statusBarColor">@android:color/transparent</item>
<!-- Set Navigation Bar color -->
<item name="android:navigationBarColor">@color/player_sheet_background</item>
<!-- Set splash screen icon background color --> <!-- Set splash screen icon background color -->
<item name="android:windowSplashScreenIconBackgroundColor">@color/splashBackgroundColor</item> <item name="android:windowSplashScreenIconBackgroundColor">@color/splashBackgroundColor</item>
</style> </style>
@@ -39,6 +39,7 @@
<item name="colorSurface">@color/player_sheet_background</item> <item name="colorSurface">@color/player_sheet_background</item>
<item name="materialAlertDialogBodyTextStyle">@style/TextAppearance.MaterialComponents.Body1</item> <item name="materialAlertDialogBodyTextStyle">@style/TextAppearance.MaterialComponents.Body1</item>
<item name="android:backgroundDimAmount">0.64</item> <item name="android:backgroundDimAmount">0.64</item>
<item name="colorControlActivated">#FFDAE2FF</item>
</style> </style>
<style name="ThemeOverlay.App.TimePicker" parent="ThemeOverlay.MaterialComponents.TimePicker"> <style name="ThemeOverlay.App.TimePicker" parent="ThemeOverlay.MaterialComponents.TimePicker">
@@ -49,5 +50,12 @@
<item name="android:background">@color/player_sheet_background</item> <item name="android:background">@color/player_sheet_background</item>
<item name="dialogCornerRadius">28dp</item> <item name="dialogCornerRadius">28dp</item>
<item name="checkedTextViewStyle">@style/AlertDialog.TextColor</item> <item name="checkedTextViewStyle">@style/AlertDialog.TextColor</item>
<item name="colorControlActivated">#FFDAE2FF</item>
<item name="colorControlHighlight">#33FFFFFF</item>
<item name="android:colorFocusedHighlight">#80FFFFFF</item>
</style>
<style name="AlertDialog.TextColor" parent="@style/TextAppearance.MaterialComponents.Body1">
<item name="android:textColor">?attr/colorControlNormal</item>
</style> </style>
</resources> </resources>
+1 -1
View File
@@ -1,5 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<!-- NIGHT THEME COLORS --> <!-- NIGHT THEME COLORS -->
@@ -32,4 +31,5 @@
<color name="player_sheet_text_main">#FFFFFFFF</color> <color name="player_sheet_text_main">#FFFFFFFF</color>
<color name="player_sheet_icon">#FFFFFFFF</color> <color name="player_sheet_icon">#FFFFFFFF</color>
<color name="cardview_reordering">#FFDAE2FF</color>
</resources> </resources>
+9
View File
@@ -7,6 +7,9 @@
<item name="colorAccent">#FFDAE2FF</item> <item name="colorAccent">#FFDAE2FF</item>
<item name="colorOnPrimary">#FF182E60</item> <item name="colorOnPrimary">#FF182E60</item>
<item name="android:textColorHighlight">#FF495D92</item> <item name="android:textColorHighlight">#FF495D92</item>
<item name="colorControlHighlight">#33FFFFFF</item>
<item name="android:colorControlHighlight">#33FFFFFF</item>
<item name="android:colorFocusedHighlight">#80FFFFFF</item>
<!-- Do not use primary colored elevation overlays to present a visual hierarchy - TOO COLORFUL --> <!-- Do not use primary colored elevation overlays to present a visual hierarchy - TOO COLORFUL -->
<item name="elevationOverlayEnabled">false</item> <item name="elevationOverlayEnabled">false</item>
@@ -24,4 +27,10 @@
<!-- Don't show light status bar --> <!-- Don't show light status bar -->
<item name="android:statusBarColor">@android:color/transparent</item> <item name="android:statusBarColor">@android:color/transparent</item>
</style> </style>
<style name="CustomCastExpandedControllerStyle" parent="CastExpandedController">
<item name="android:windowBackground">#FFFFFF</item>
<item name="castBackground">#FFFFFF</item>
<item name="castButtonColor">#FF495D92</item>
</style>
</resources> </resources>
+2 -2
View File
@@ -63,7 +63,7 @@
<string name="pref_edit_station_title">Редактировать станции</string> <string name="pref_edit_station_title">Редактировать станции</string>
<string name="pref_general_title">Общие</string> <string name="pref_general_title">Общие</string>
<string name="pref_license_title">Это приложение с открытым исходным кодом</string> <string name="pref_license_title">Это приложение с открытым исходным кодом</string>
<string name="pref_license_summary">Лицензировано под лицензией MIT</string> <string name="pref_license_summary">Лицензировано под лицензией GPLv3</string>
<string name="pref_links_title">Ссылки</string> <string name="pref_links_title">Ссылки</string>
<string name="pref_m3u_export_summary">Сохраните ваши радиостанции в файл плейлиста M3U, который можно импортировать в другие проигрыватели.</string> <string name="pref_m3u_export_summary">Сохраните ваши радиостанции в файл плейлиста M3U, который можно импортировать в другие проигрыватели.</string>
<string name="pref_m3u_export_title">Экспорт M3U</string> <string name="pref_m3u_export_title">Экспорт M3U</string>
@@ -98,7 +98,7 @@
<string name="toastmessage_preview_playback_started">Было запущено воспроизведение предварительного просмотра.</string> <string name="toastmessage_preview_playback_started">Было запущено воспроизведение предварительного просмотра.</string>
<string name="toastmessage_restored">Станции были успешно восстановлены.</string> <string name="toastmessage_restored">Станции были успешно восстановлены.</string>
<string name="toastmessage_save_m3u">Сохранение радиостанций как M3U…</string> <string name="toastmessage_save_m3u">Сохранение радиостанций как M3U…</string>
<string name="toastmessage_save_pls">Сохранение радиостанций в формате PLS...</string> <string name="toastmessage_save_pls">Сохранение радиостанций в формате PLS</string>
<string name="toastmessage_shortcut_created">Ярлык создан.</string> <string name="toastmessage_shortcut_created">Ярлык создан.</string>
<string name="toastmessage_shortcut_not_created">Ярлык не создан. Устройство не позволяет создавать ярлыки.</string> <string name="toastmessage_shortcut_not_created">Ярлык не создан. Устройство не позволяет создавать ярлыки.</string>
<string name="toastmessage_sleep_timer_unable_to_start">Пожалуйста, запустите сперва воспроизведение.</string> <string name="toastmessage_sleep_timer_unable_to_start">Пожалуйста, запустите сперва воспроизведение.</string>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="SplashTheme" parent="Theme.Material3.DayNight.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
<item name="android:statusBarColor">@color/splashBackgroundColor</item>
</style>
</resources>
+1 -1
View File
@@ -63,7 +63,7 @@
<string name="pref_edit_station_title">Редагувати станції</string> <string name="pref_edit_station_title">Редагувати станції</string>
<string name="pref_general_title">Загальні</string> <string name="pref_general_title">Загальні</string>
<string name="pref_license_title">Цей застосунок має відкритий початковий код</string> <string name="pref_license_title">Цей застосунок має відкритий початковий код</string>
<string name="pref_license_summary">На умовах ліцензії MIT</string> <string name="pref_license_summary">На умовах ліцензії GPLv3</string>
<string name="pref_links_title">Посилання</string> <string name="pref_links_title">Посилання</string>
<string name="pref_m3u_export_summary">Збережіть свої радіостанції у файлі списку відтворення M3U, який можна імпортувати в інші програвачі.</string> <string name="pref_m3u_export_summary">Збережіть свої радіостанції у файлі списку відтворення M3U, який можна імпортувати в інші програвачі.</string>
<string name="pref_m3u_export_title">Експорт M3U</string> <string name="pref_m3u_export_title">Експорт M3U</string>
-26
View File
@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Set AppCompats colors -->
<item name="colorPrimary">#FF495D92</item>
<item name="colorAccent">#FF495D92</item>
<item name="android:textColorHighlight">#FF495D92</item>
<!-- Do not use primary colored elevation overlays to present a visual hierarchy - TOO COLORFUL -->
<item name="elevationOverlayEnabled">false</item>
<!-- Switch Theming -->
<item name="switchPreferenceCompatStyle">@style/Preference.SwitchPreferenceCompat.Material3</item>
<!-- Material Alert Dialog Theming -->
<item name="alertDialogTheme">@style/ThemeOverlay.App.AlertDialogTheme</item>
<!-- Use "light" Status Bar -->
<item name="android:windowLightStatusBar">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<!-- Use "light" Navigation Bar -->
<item name="android:windowLightNavigationBar">true</item>
</style>
</resources>

Some files were not shown because too many files have changed in this diff Show More