<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cosmin Mihu on Medium]]></title>
        <description><![CDATA[Stories by Cosmin Mihu on Medium]]></description>
        <link>https://medium.com/@cosmin.mihu?source=rss-33795083ab25------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jb6AoffxdIlADP_Vr_5pcw.jpeg</url>
            <title>Stories by Cosmin Mihu on Medium</title>
            <link>https://medium.com/@cosmin.mihu?source=rss-33795083ab25------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:06:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cosmin.mihu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Deep Linking Made Simple with Navigation 3]]></title>
            <link>https://medium.com/@cosmin.mihu/android-deep-linking-made-simple-with-navigation-3-44e29735b5d0?source=rss-33795083ab25------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e29735b5d0</guid>
            <dc:creator><![CDATA[Cosmin Mihu]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 16:06:19 GMT</pubDate>
            <atom:updated>2026-07-30T16:34:50.810Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep linking has historically been one of the most fragile parts of Android development. From managing complex Intent filters in AndroidManifest.xml to handling string-based routes and reflection-like parameter parsing in Navigation Component (V2), there was always a risk of runtime crashes due to a typo in a URL or a missing query parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwND-fKproCnzNFShxb3ZA.png" /></figure><p>Early iterations of <strong>Navigation 3</strong> brought explicit, user-owned state control over the backstack, but URL parsing was still a manual recipe. Starting with 1.2.0-alpha07 release, Google has introduced <strong>native deep link handling support directly into the library</strong>.</p><p>Here is how you can leverage Navigation 3’s built-in deep linking tools to keep your codebase clean, type-safe, and robust.</p><h3>0. Project Setup</h3><p>Before we dive into the code, ensure you have the necessary dependencies in your Version Catalog (libs.versions.toml):</p><pre>[versions]<br># Navigation 3 with built-in deep link support<br>navigation = &quot;1.2.0-alpha07&quot;<br>kotlin = &quot;2.4.10&quot;<br><br>[libraries]<br>androidx-navigation3-runtime = { module = &quot;androidx.navigation3:navigation3-runtime&quot;, version.ref = &quot;navigation&quot; }<br>androidx-navigation3-ui = { module = &quot;androidx.navigation3:navigation3-ui&quot;, version.ref = &quot;navigation&quot; }<br><br>[plugins]<br># Serialization is required for typed NavKey parsing<br>kotlin-serialization = { id = &quot;org.jetbrains.kotlin.plugin.serialization&quot;, version.ref = &quot;kotlin&quot; }</pre><p>Then, apply them in your module’s build.gradle.kts:</p><pre>plugins {<br>    alias(libs.plugins.kotlin.serialization)<br>}<br><br>dependencies {<br>    implementation(libs.androidx.navigation3.runtime)<br>    implementation(libs.androidx.navigation3.ui)<br>}</pre><h3>1. Configuring AndroidManifest.xml</h3><p>Before Navigation 3 can process any incoming deep links, Android needs to know which URLs or URIs your application is eligible to handle. You achieve this by registering an &lt;intent-filter&gt; inside your main Activity declaration in AndroidManifest.xml.</p><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:exported=&quot;true&quot;<br>    android:launchMode=&quot;singleTask&quot;&gt;<br><br>    &lt;!-- Standard Launcher Intent Filter --&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>        &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>    &lt;/intent-filter&gt;<br><br>    &lt;!-- Deep Link Intent Filter --&gt;<br>    &lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>        &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br><br>        &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>        &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br><br>        &lt;!-- Web App Links (e.g., https://cosminmihu.ro/profile/123) --&gt;<br>        &lt;data<br>            android:scheme=&quot;https&quot;<br>            android:host=&quot;cosminmihu.ro&quot; /&gt;<br>    &lt;/intent-filter&gt;<br><br>&lt;/activity&gt;</pre><blockquote>See details <a href="https://developer.android.com/training/app-links/configure-assetlinks">here</a> to configure <strong>App Links (https scheme)</strong>. All other deep link types are already functioning fine.</blockquote><h3>2. The Foundation: Type-Safe NavKey</h3><p>In Navigation 3, destinations are no longer string routes like &quot;profile/{id}&quot;. Every screen is backed by a serializable Kotlin class/object known as a NavKey:</p><pre>@Serializable<br>data class ProfileKey(val userId: String) : NavKey<br><br>@Serializable<br>data object HomeKey : NavKey</pre><h3>3. What’s New: Native Matchers in Navigation 3</h3><p>Instead of manually splitting URI path segments or writing custom regex matchers, Navigation 3 now offers built-in matchers like UriDeepLinkMatcher out of the box.</p><p>You can declare how a URL pattern bridges to your NavKey serializer directly:</p><pre>val profileMatcher = UriDeepLinkMatcher(<br>    uriPattern = DeepLinkUri(&quot;https://cosminmihu.ro/user/{userId}&quot;),<br>    serializer = ProfileKey.serializer()<br>)<br><br>val allMatchers = listOf(profileMatcher)</pre><blockquote><strong>How it works under the hood:</strong> The native matcher automatically extracts {userId} from the incoming URL pattern, matches its argument types, and maps it directly into the fields of your <em>@Serializable </em><em>ProfileKey.</em></blockquote><h3>4. Native Intent-to-Key Conversion</h3><p>With native DeepLinkRequest support, converting an incoming Uri or Intent into a target NavKey requires just a few lines of functional code:</p><pre>fun Uri.toNavKey(): NavKey {<br>    // Wrap the incoming URI into a DeepLinkRequest (supported directly by Nav 3)<br>    val request = DeepLinkRequest(this.toString())<br>    <br>    // Find the first matching pattern<br>    val match = allMatchers.firstNotNullOfOrNull { it.match(request) }<br>    <br>    // Return the strongly-typed key, or fall back to Home<br>    return match?.key ?: HomeKey<br>}</pre><h3>5. Jetpack Compose Integration</h3><p>Because Navigation 3 treats the backstack as a simple, reactive list (SnapshotStateList), setting up your initial destination from a deep link URI is seamless:</p><pre>@Composable<br>fun MainApp(startingUri: Uri?) {<br>    // Resolve the incoming URI to a typed NavKey on launch<br>    val initialKey = remember(startingUri) { <br>        startingUri?.toNavKey() ?: HomeKey <br>    }<br>    <br>    val backStack = rememberNavBackStack(initialKey)<br>    <br>    NavDisplay(<br>        backStack = backStack,<br>        onBack = { backStack.removeLastOrNull() },<br>        entryProvider = myEntryProvider<br>    )<br>}</pre><h3>6. Testing Your Deep Links</h3><p>Verify your implementation easily from your terminal using adb without needing a browser or external app:</p><pre>adb shell am start -W -a android.intent.action.VIEW -d &quot;https://cosminmihu.ro/user/123&quot;</pre><h3>Why Is This Native Approach Better?</h3><ul><li><strong>Zero Boilerplate Parsing:</strong> No custom decoders or manual string slicing — UriDeepLinkMatcher and DeepLinkRequest handle URI decoding internally using Kotlin Serialization.</li><li><strong>Compile-Time Safety:</strong> If you rename a parameter in ProfileKey, you are forced to update your serializer mappings immediately.</li><li><strong>Direct Backstack Control:</strong> You are in full control of state initialization. You can easily construct synthetic backstacks (e.g., placing HomeKey behind ProfileKey) without fighting the library.</li></ul><h3>Conclusion</h3><p>By baking deep link matching and request abstractions directly into the library, Navigation 3 removes the manual overhead while preserving total control over your app’s backstack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e29735b5d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android MCP — App Functions: Let AI call Android App]]></title>
            <link>https://medium.com/@cosmin.mihu/android-mcp-app-functions-let-ai-call-android-app-0cedb40a4cae?source=rss-33795083ab25------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cedb40a4cae</guid>
            <category><![CDATA[function-app]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Cosmin Mihu]]></dc:creator>
            <pubDate>Fri, 15 May 2026 14:10:47 GMT</pubDate>
            <atom:updated>2026-08-14T08:02:35.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4QKCI0qzl_25iIVYhWK_Q.png" /></figure><p><em>Expose your app’s capabilities to AI assistants/agents using the androidx App Functions API</em></p><h2>Introduction</h2><p>For years, mobile development has revolved around UI, navigation graphs, and deep links. But with the rise of on-device intelligence and autonomous AI agents, apps need to expose <strong>executable capabilities</strong>, not just views.</p><p>Android’s <strong>AppFunctions API</strong> serves as the standard contract between your app’s business logic and AI agents. Think of it as <strong>MCP (Model Context Protocol) natively embedded into Android</strong>: it allows agents to discover, understand, and invoke your app’s functions securely in the background.</p><p>For easy implementation, there’s already an <strong>Android Skill specifically designed for implementing AppFunctions</strong>. It provides guidance and practical instructions for exposing your app’s capabilities to AI agents: <a href="https://github.com/android/skills/blob/main/device-ai/appfunctions/SKILL.md?utm_source=chatgpt.com">Android AppFunctions Skill</a>.</p><h2>Step 1. Dependencies</h2><pre>// build.gradle.kts<br>android {<br>    compileSdk = 36<br>}<br><br>dependencies {<br>    implementation(libs.appfunctions)<br>    ksp(libs.appfunctions.compiler)<br>}<br><br>ksp {<br>    arg(&quot;appfunctions:aggregateAppFunctions&quot;, &quot;true&quot;)<br>}</pre><pre># libs.versions.toml<br>[versions]<br>appfunctions = &quot;1.0.0-alpha10&quot;<br><br>[libraries]<br>appfunctions          = { module = &quot;androidx.appfunctions:appfunctions&quot;,          version.ref = &quot;appfunctions&quot; }<br>appfunctions-compiler = { module = &quot;androidx.appfunctions:appfunctions-compiler&quot;, version.ref = &quot;appfunctions&quot; }</pre><h2>Step 2. Define Serializable AppFunction Types</h2><p>Any type returned by an App Function must be annotated with @AppFunctionSerializable. The KDoc comment becomes <strong>semantic metadata</strong> that helps AI agents understand the data.</p><pre>/**<br> * Represents the word of the day.<br> */<br>@AppFunctionSerializable(isDescribedByKDoc = true)<br>data class TodayWord(<br>    /** The word the word of the day */<br>    val word: String,<br>    /** The definition of the word */<br>    val definition: String,<br>)</pre><h2>Step 3: Implement business logic</h2><pre>class GetTodayWordUseCaseAppFunction(<br>    private val dayWordRepository: DayWordRepository<br>) {<br>    <br>    /**<br>     * Gets today&#39;s word along with its definition.<br>     *<br>     * @return a [TodayWord] with the word and its plain text definition,<br>     * or `null` if no word is available for today<br>     */<br>    suspend operator fun invoke(): TodayWord? {<br>        val today = LocalDate.now()<br>        val data = dayWordRepository.getDayWord(today).data ?: return null<br>        return TodayWord(data.word, data.definition.htmlRep.removeHtmlTags())<br>    }<br>}</pre><h2>Step 4: <em>The service entry point</em></h2><pre>@RequiresApi(36)<br>@AppFunctionServiceEntryPoint(<br>    serviceName = &quot;DexAppFunctionService&quot;,<br>    appFunctionXmlFileName = &quot;dex_app_function_service&quot;,<br>)<br>abstract class BaseDexAppFunctionService : AppFunctionService(), KoinComponent {<br><br>    /** Resolved via Koin DI */<br>    private val getTodayWordUseCase: GetTodayWordUseCaseAppFunction by inject()<br><br>    /**<br>     * Retrieves today&#39;s word and its definition.<br>     *<br>     * @return A [TodayWord] with the word and its definition,<br>     * or `null` if no word is available for today.<br>     */<br>    @AppFunction(isDescribedByKDoc = true)<br>    suspend fun getTodayWord(): TodayWord? = withContext(Dispatchers.IO) {<br>        getTodayWordUseCase()<br>    }<br>}</pre><p>The lambda delegates to <strong>Koin</strong> (inject()), so the full dependency graph (repository → network/database) is wired in automatically.</p><h2>Step 5: Declare service in AndroidManifest</h2><p>Register the KSP-generated concrete service and point the metadata properties at the generated files:</p><pre>&lt;!-- App Functions --&gt;<br>&lt;service<br>    android:name=&quot;.appfunctions.DexAppFunctionService&quot;<br>    android:permission=&quot;android.permission.BIND_APP_FUNCTION_SERVICE&quot;<br>    android:exported=&quot;true&quot;<br>    tools:targetApi=&quot;36&quot;&gt;<br>    &lt;property<br>        android:name=&quot;android.app.appfunctions.schema&quot;<br>        android:value=&quot;app_functions_schema.xsd&quot; /&gt;<br>    &lt;property<br>        android:name=&quot;android.app.appfunctions.v2&quot;<br>        android:value=&quot;dex_app_function_service.xml&quot; /&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.app.appfunctions.AppFunctionService&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;<br><br>&lt;property<br>    android:name=&quot;android.app.appfunctions.app_metadata&quot;<br>    android:resource=&quot;@xml/app_functions_metadata&quot; /&gt;</pre><p>The <strong>BIND_APP_FUNCTION_SERVICE</strong> permission ensures the system can bind to the service.</p><pre>&lt;!-- res/xml/app_functions_metadata.xml --&gt;<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;AppFunctionAppMetadata <br>    xmlns:appfn=&quot;http://schemas.android.com/apk/androidx.appfunctions&quot;<br>    appfn:displayDescription=&quot;@string/app_functions_description&quot;<br>    appfn:description=<br>&quot;<br>DexMobile provides access to the DEX Online Romanian dictionary.<br><br>Operational Patterns:<br>- Use &#39;getTodayWord&#39; to retrieve the word of the day and its definition without opening the app.<br><br>Constraints:<br>- &#39;getTodayWord&#39; returns null when no word has been published for the current date.<br>&quot;<br> /&gt;</pre><h2>Step 6: Test with ADB</h2><pre>adb shell cmd app_function execute-app-function \<br>  --package com.mdc.mobiledex.v1 \<br>  --function &quot;GetTodayWordUseCaseAppFunction#invoke&quot; \<br>  --parameters &quot;{}&quot;</pre><p>Expected response:</p><pre>{<br>  &quot;word&quot;: &quot;serendipitate&quot;,<br>  &quot;definition&quot;: &quot;Capacitatea de a face descoperiri fericite din întâmplare.&quot;<br>}</pre><h2>Best Practices</h2><ol><li><strong>Write thorough KDoc.</strong> The AI’s ability to understand when to call your function depends entirely on your documentation.</li><li><strong>Keep functions focused.</strong> One function, one responsibility — treat them like API endpoints.</li><li><strong>Use DI for factory resolution.</strong> App Functions benefit from the same dependency wiring as the rest of your app.</li><li><strong>Handle </strong><strong>null gracefully.</strong> Return null when data isn&#39;t available rather than throwing exceptions.</li></ol><h2>Conclusion</h2><p>With just a few lines of code, DexMobile’s “Word of the Day” feature is accessible to any AI assistant that speaks App Functions — no custom intents, no separate API to maintain. The KSP tooling handles all the boilerplate, you focus on business logic.</p><p>The future of Android apps isn’t just screens — it’s exposing capabilities that AI agents can orchestrate for users. App Functions are the bridge.</p><p><em>Further reading: </em><a href="https://developer.android.com/ai/appfunctions/add-appfunctions"><em>App Functions — Android Developers</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cedb40a4cae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KtorMonitor: Debug and Analyze Ktor Client Network Traffic]]></title>
            <link>https://medium.com/@cosmin.mihu/ktormonitor-debug-and-analyze-ktor-client-network-traffic-411c66061baf?source=rss-33795083ab25------2</link>
            <guid isPermaLink="false">https://medium.com/p/411c66061baf</guid>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Cosmin Mihu]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 15:25:01 GMT</pubDate>
            <atom:updated>2026-02-02T15:25:01.032Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IbphFZDBwtcrMqzgLtgNSA.png" /></figure><p>Debugging network issues shouldn’t feel like guesswork. When working with <a href="https://ktor.io/"><strong>Ktor Client</strong></a>, understanding exactly what requests are sent and how responses are received is critical — but often harder than it should be.</p><p><strong>KtorMonitor</strong> is a powerful monitoring tool that gives full visibility into <a href="https://ktor.io/">Ktor Client</a> network traffic, making it effortless to inspect requests and responses in real time. With clear insights and an intuitive approach, you can quickly identify issues, analyze behavior, and debug network communication with confidence.</p><p>👉 <strong>Explore the project on GitHub: </strong><a href="https://github.com/CosminMihuMDC/KtorMonitor/">https://github.com/CosminMihuMDC/KtorMonitor/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axoUDv23bffUjOtNFMPmaQ.png" /></figure><h3>✨ Features</h3><ul><li>🌐<strong>Ktor Network Monitoring</strong>: Real-time interception and logging of <a href="https://ktor.io/">Ktor Client</a> traffic.</li><li>📱<strong>Kotlin Multiplatform (KMP)</strong>: Full support for <strong>Android, iOS, Desktop (JVM), Wasm, </strong>and<strong> JS</strong>.</li><li>🛠️<strong>Highly Configurable</strong>: Customize retention periods, content length limits, and notification behavior.</li><li>🔒<strong>Security First</strong>: Redact sensitive headers (e.g., <em>Authorization</em>).</li><li>📂<strong>Data Export</strong>: Save request/response details to local files for easier debugging or sharing.</li><li>🎨<strong>Rich Previews</strong>: Built-in viewers for <em>JSON</em>, <em>XML</em>, <em>HTML</em>, <em>CSS</em>, <em>Form Data</em>, <em>Image</em> (<em>JPG</em>, <em>PNG</em>, <em>SVG</em>, <em>GIF</em>, <em>WEBP</em>).</li><li>📡<strong>SSE &amp; WebSockets</strong>: Track one-way streams (<em>SSE</em>) and bidirectional traffic (<em>WebSockets</em>).</li><li>🛡️<strong>Production Safe</strong>: No-Op version to ensure monitoring code is excluded from your production builds.</li></ul><h3>📦 Setup (Kotlin Multiplatform)</h3><pre>kotlin {<br>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(&quot;ro.cosminmihu.ktor:ktor-monitor-logging:1.10.0&quot;)<br>        }<br>    }<br>}</pre><p><strong>For Release Builds (No-Op)</strong></p><p>To isolate KtorMonitor from release builds, use the ktor-monitor-logging-no-op variant. This ensures the monitor code is not included in production artifact.</p><pre>kotlin {<br>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(&quot;ro.cosminmihu.ktor:ktor-monitor-logging-no-op:1.10.0&quot;)<br>        }<br>    }<br>}</pre><h3>📦 Setup (Android only)</h3><pre>dependencies {<br>    debugImplementation(&quot;ro.cosminmihu.ktor:ktor-monitor-logging:1.10.0&quot;)<br>    releaseImplementation(&quot;ro.cosminmihu.ktor:ktor-monitor-logging-no-op:1.10.0&quot;)<br>}</pre><p>For <strong><em>Android minSdk &lt; 26</em></strong>, <a href="https://developer.android.com/studio/write/java8-support#library-desugaring">Core Library Desugaring</a> is required.</p><h3>⚙️ Install Ktor Client Plugin</h3><pre>HttpClient {<br>    install(KtorMonitorLogging) {  <br>        sanitizeHeader { header -&gt; header == &quot;Authorization&quot; }  <br>        filter { request -&gt; !request.url.host.contains(&quot;cosminmihu.ro&quot;) }  <br>        showNotification = true  <br>        retentionPeriod = RetentionPeriod.OneHour<br>        maxContentLength = ContentLength.Default<br>    }<br>}</pre><ul><li>sanitizeHeader - sanitize sensitive headers to avoid their values appearing in the logs</li><li>filter - filter logs for calls matching a predicate.</li><li>showNotification - Keep track of latest requests and responses into notification. Default is true. Android and iOS only. Notifications permission needs to be granted.</li><li>retentionPeriod - The retention period for the logs. Default is 1h.</li><li>maxContentLength - The maximum length of the content that will be logged. After this, body will be truncated. Default is <strong>250_000</strong>. To log the entire body use ContentLength.Full.</li></ul><h3>🧩 Integration</h3><p>Add the UI component to your application based on your targeted platform.</p><p><strong>Compose Multiplatform (Common)</strong></p><ul><li>Use KtorMonitor Composable</li></ul><pre>@Composable<br>fun Composable() {<br>    KtorMonitor()<br>}</pre><p><strong>Android</strong></p><ul><li>If showNotifcation = true and <strong>android.permission.POST_NOTIFICATIONS</strong> is granted, the library will display a notification showing a summary of ongoing KTOR activity. Tapping on the notification launches the full KtorMonitor.</li><li>Apps can optionally use the KtorMonitor() Composable directly into own Composable code.</li><li>For <em>Android minSdk &lt; 26</em>, <a href="https://developer.android.com/studio/write/java8-support#library-desugaring">Core Library Desugaring</a> is required.</li></ul><p><strong>iOS</strong></p><ul><li>If showNotifcation = true and notification permission is granted, the library will display a notification showing a summary of ongoing KTOR activity.</li><li>Use KtorMonitorViewController</li></ul><pre>fun MainViewController() = KtorMonitorViewController()</pre><pre>struct KtorMonitorView: UIViewControllerRepresentable {<br>    func makeUIViewController(context: Context) -&gt; UIViewController {<br>        MainViewControllerKt.MainViewController()<br>    }<br><br>    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}<br>}<br><br>struct ContentView: View {<br>    var body: some View {<br>        KtorMonitorView()<br>            .ignoresSafeArea()<br>    }<br>}</pre><p><strong>Desktop (Compose)</strong></p><ul><li>Use KtorMonitorWindow Composable</li></ul><pre>fun main() = application {<br>    var showKtorMonitor by rememberSaveable { mutableStateOf(false) }<br>    KtorMonitorWindow(<br>        onCloseRequest = { showKtorMonitor = false },<br>        show = showKtorMonitor<br>    )<br>}</pre><ul><li>Use KtorMonitorWindow Composable with KtorMonitorMenuItem</li></ul><pre>fun main() = application {<br>    var showKtorMonitor by rememberSaveable { mutableStateOf(false) }<br>    Tray(<br>        icon = painterResource(Res.drawable.ic_launcher),<br>        menu = {<br>            KtorMonitorMenuItem { showKtorMonitor = true }<br>        }<br>    )<br>    KtorMonitorWindow(<br>        show = showKtorMonitor,<br>        onCloseRequest = { showKtorMonitor = false }<br>    )<br>}</pre><p><strong>Desktop (Swing)</strong></p><ul><li>Use KtorMonitorPanel Swing Panel</li></ul><pre>fun main() = application {<br>    SwingUtilities.invokeLater {<br>        val frame = JFrame()<br>        frame.add(KtorMonitorPanel, BorderLayout.CENTER)<br>        frame.isVisible = true<br>    }<br>}</pre><p><strong>Wasm / Js</strong></p><ul><li>Web targets require a few additional webpack steps.</li></ul><pre>kotlin {<br>    sourceSets {<br>        webMain.dependencies {<br>            implementation(devNpm(&quot;copy-webpack-plugin&quot;, &quot;9.1.0&quot;))<br>        }<br>    }<br>}</pre><pre>// {project}/webpack.config.d/sqljs.js<br>config.resolve = {<br>    fallback: {<br>        fs: false,<br>        path: false,<br>        crypto: false,<br>    }<br>};</pre><pre>const CopyWebpackPlugin = require(&#39;copy-webpack-plugin&#39;);<br>config.plugins.push(<br>    new CopyWebpackPlugin({<br>        patterns: [<br>            &#39;../../node_modules/sql.js/dist/sql-wasm.wasm&#39;<br>        ]<br>    })<br>);</pre><pre>ComposeViewport {<br>    App()<br>}</pre><h3>✍️ Feedback</h3><p>Found a bug or have a feature request? <a href="https://github.com/CosminMihuMDC/KtorMonitor/issues/new">File an issue</a>.</p><h3>🙌 Acknowledgments</h3><p>Community discussions on <strong>Slack</strong> — join us in the <a href="https://kotlinlang.slack.com/archives/C0AB9GA32H0">#ktormonitor</a> channel.<br><strong>Documentation</strong> is available at <a href="https://cosminmihumdc.github.io/KtorMonitor">KtorMonitor Documentation</a>.<br><strong>API</strong> is available at <a href="https://cosminmihumdc.github.io/KtorMonitor/api">KtorMonitor API</a>.<br>KtorMonitor is available also on JetBrains’ <a href="https://klibs.io/project/CosminMihuMDC/KtorMonitor">klibs.io</a>.</p><h3>💸 Sponsors</h3><p>KtorMonitor is maintained and improved during nights, weekends and whenever team has free time. If you use KtorMonitor in your project, please consider sponsoring us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*LvMrqCuaSJ6_eig7" /></figure><h3>🙏🏻 Credits</h3><p><strong>KtorMonitor</strong> is brought to you by these <a href="https://github.com/CosminMihuMDC/KtorMonitor/graphs/contributors">contributors</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=411c66061baf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture with KOTLIN]]></title>
            <link>https://medium.com/@cosmin.mihu/clean-architecture-with-kotlin-97e246d0361b?source=rss-33795083ab25------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e246d0361b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Cosmin Mihu]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 13:20:59 GMT</pubDate>
            <atom:updated>2022-06-04T13:20:59.311Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Overview</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJ8rrWLTznH1-uidm-WvWQ.png" /></figure><p>2. Data Sources</p><ul><li>work with only raw data</li><li>type of data sources: network, database, file, prefs, bluetooth, location manager, other platform hardware sensors, …</li></ul><p>3. Repository</p><ul><li>aggregate &amp; merge different sources of data</li><li>work mainly with raw data</li></ul><p>4. Use Case</p><ul><li>business logic</li><li>aggregate data from multiple repositories</li></ul><p>5. View Model</p><ul><li>aggregate data from use cases</li><li>prepare data to be shown on UI</li><li>UI logic</li></ul><p>6. UI</p><ul><li>Display data from view model</li><li>Compose, View, FX, Swing, …</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e246d0361b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Background Audio Player with Jetpack Media3]]></title>
            <link>https://medium.com/@cosmin.mihu/android-background-audio-player-with-jetpack-media3-ba441567f533?source=rss-33795083ab25------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba441567f533</guid>
            <category><![CDATA[background-player]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[audiolayer]]></category>
            <category><![CDATA[jetpack-media3]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Cosmin Mihu]]></dc:creator>
            <pubDate>Tue, 17 May 2022 14:20:42 GMT</pubDate>
            <atom:updated>2022-05-17T14:25:00.944Z</atom:updated>
            <content:encoded><![CDATA[<p>How to create a simple audio player for Android that can play also in background? What is the right way to play audio in background and foreground?</p><h3>Sample Source Code</h3><p><a href="https://github.com/CosminMihuMDC/AndroidAudioServiceSample">https://github.com/CosminMihuMDC/AndroidAudioServiceSample</a></p><h3>Why Jetpack Media3?</h3><p>Media3 provides a single set of libraries which work well together.</p><p><strong>Disclaimer</strong>: Media3 is in alpha.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsTIBDcyCmCg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsTIBDcyCmCg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsTIBDcyCmCg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/06b09b6d0b4d2bad1e5980d8934f06f8/href">https://medium.com/media/06b09b6d0b4d2bad1e5980d8934f06f8/href</a></iframe><h3>1. Create Audio Service</h3><ul><li>Create <em>ExoPlayer</em> (and customize it — Noisy, Wake).</li><li>Create <em>MediaLibrarySessionCallback</em>: used to get media items from data sources asynchronous using a tree structure (root and children) (<a href="https://developer.android.com/reference/android/media/browse/MediaBrowser"><em>https://developer.android.com/reference/android/media/browse/MediaBrowser</em></a><em>).</em></li><li>Create <em>MediaItemFiller</em>: used to fill in the localConfiguration of the media item.</li><li>Create <em>MediaLibrarySession</em>.</li></ul><pre>class AudioService : <strong>MediaLibraryService</strong>() {<br><br>    private lateinit var player: ExoPlayer<br>    private lateinit var mediaLibrarySession: MediaLibrarySession<br>    private val audioDataSource: AudioDataSource by <em>inject</em>()<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        initializeSessionAndPlayer()<br>    }<br><br>    override fun onDestroy() {<br>        player.release()<br>        mediaLibrarySession.release()<br>        super.onDestroy()<br>    }<br><br>    override fun <strong>onGetSession</strong>(controllerInfo: MediaSession.ControllerInfo) = mediaLibrarySession<br><br>    private fun initializeSessionAndPlayer() {<br>        <strong>player</strong> = ExoPlayer.Builder(this)<br>            .setAudioAttributes(AudioAttributes.<em>DEFAULT</em>, true)<br>            .setHandleAudioBecomingNoisy(true)<br>            .setWakeMode(C.<em>WAKE_MODE_LOCAL</em>)<br>            .build()<br><br>        val pendingIntent = buildPendingIntent()<br>        val sessionCallback = AudioMediaLibrarySessionCallback(audioDataSource, player)<br><br>        <strong>mediaLibrarySession</strong> = MediaLibrarySession.Builder(this, player, sessionCallback)<br>            .setSessionActivity(pendingIntent)<br>            .setMediaItemFiller(AudioMediaItemFiller(audioDataSource))<br>            .build()<br>    }<br><br>    private fun buildPendingIntent(): PendingIntent {<br>        val intent = Intent(this, MainActivity::class.<em>java</em>)<br>        val pendingIntent = TaskStackBuilder.create(this).<em>run </em><strong>{<br>            </strong>addNextIntent(intent)<br>            getPendingIntent(0, PendingIntent.<em>FLAG_IMMUTABLE </em>or PendingIntent.<em>FLAG_UPDATE_CURRENT</em>)<br>        <strong>}<br>        </strong>return pendingIntent<br>    }<br>}</pre><h4>Update AndroidManifest.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br><br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.<strong>FOREGROUND_SERVICE</strong>&quot; /&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.<strong>WAKE_LOCK</strong>&quot; /&gt;<br><br>    &lt;application ..... &gt;</pre><pre>       &lt;service<br>            android:name=&quot;.service.AudioService&quot;<br>            android:exported=&quot;false&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;<strong>androidx.media3.session.MediaSessionService</strong>&quot; /&gt;<br>                &lt;action android:name=&quot;<strong>android.media.browse.MediaBrowserService</strong>&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/service&gt;</pre><pre>&lt;/manifest&gt;</pre><p>That’s pretty much it with the service. Now we are able to play different media items in background and foreground, and also the entire stuff, like notification and so on, are already done by media3.</p><h3>2. Show media items in Activity/Fragment</h3><p>Now we have to interrogate the service and show media items in activity/fragment by using <em>MediaBrowser.</em></p><pre>class MainActivity : ComponentActivity() {<br>    <strong>private lateinit var browserFuture: ListenableFuture&lt;MediaBrowser&gt;<br>    private val browser: MediaBrowser?<br>        get() = if (browserFuture.<em>isDone</em>) browserFuture.get() else null</strong><br><br>    override fun onStart() {<br>        super.onStart()<br>        initialize()<br>    }<br><br>    override fun onStop() {<br>        release()<br>        super.onStop()<br>    }<br><br>    private fun initialize() {<br>        val sessionToken = SessionToken(this, ComponentName(this, AudioService::class.<em>java</em>))<br><br>        browserFuture = <strong>MediaBrowser.Builder(this, sessionToken).buildAsync()</strong><br>        browserFuture.addListener(<br>            <strong>{<br>                </strong><em>// here we can get the root of media items tree or we can get also the children if it is an album for example.</em><br>            <strong>}</strong>,<br>            MoreExecutors.directExecutor()<br>        )<br>    }<br><br>    private fun release() {<br>        <strong>MediaBrowser.releaseFuture(browserFuture)</strong><br>    }</pre><pre>.......<br>}</pre><p>Using <em>MediaBrowser</em> we can navigate through media items tree. To do that, we can use:</p><ul><li>mediaBrowser<strong>.getLibraryRoot</strong>:<strong> </strong>to get the root of media items tree</li><li>mediaBrowser<strong>.getChildren</strong>:<strong> </strong>to get the children of the given media item id</li></ul><h3>3. Set and PLAY media items.</h3><p>We displayed the media items tree in Activity, now when we tap on a media item, which is not album or root, we want to load the album and play the selected media item.</p><pre>class AlbumActivity : ComponentActivity() {<br><br>    private fun <strong>playAlbum</strong>(songs: List&lt;MediaItem&gt;?, song: MediaItem) {<br>        val browser = browser ?: return<br>        if (songs.<em>isNullOrEmpty</em>()) return<br><br>        val position = songs.<em>indexOfFirst </em><strong>{ it</strong>.mediaId == song.mediaId <strong>}<br><br>        with(browser) {<br>            setMediaItems(songs)<br>            shuffleModeEnabled = false<br>            prepare()<br>            seekToDefaultPosition(position)<br>            play()<br>        }<br>    </strong>}<br>}</pre><p>That’s it. ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba441567f533" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>