<?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 Hakan Cevik on Medium]]></title>
        <description><![CDATA[Stories by Hakan Cevik on Medium]]></description>
        <link>https://medium.com/@hakanxcevik7?source=rss-5902460faa66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mXLUGpZCK1yrZE50qM1Tqw.jpeg</url>
            <title>Stories by Hakan Cevik on Medium</title>
            <link>https://medium.com/@hakanxcevik7?source=rss-5902460faa66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:00:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hakanxcevik7/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 App Startup Library: Optimize Your App’s Startup]]></title>
            <link>https://medium.com/@hakanxcevik7/android-app-startup-library-optimize-your-apps-startup-088715f81116?source=rss-5902460faa66------2</link>
            <guid isPermaLink="false">https://medium.com/p/088715f81116</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cold-start-optimization]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <category><![CDATA[hot-start]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Hakan Cevik]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 10:37:19 GMT</pubDate>
            <atom:updated>2025-12-09T11:47:35.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrqP8kSRu_KFmKbxbandZA.png" /><figcaption>App Startup Jetpack Library</figcaption></figure><p>For Android developers, the app startup process is a critical factor that directly impacts user experience. Initializations performed before the splash screen or the first activity loads can cause delays and increase user abandonment rates — studies from Google Play indicate that up to 20% of users abandon apps in the first two seconds due to slow loading. The App Startup library, a key component of Android Jetpack, addresses this by providing a streamlined, efficient way to handle component initialization. Stable since version 1.0.0 and currently at version 1.2.0 (as of October 2025), it automates the discovery and execution of initialization logic for SDKs, services, and managers that traditionally cluttered the Application.onCreate() method.</p><p>In this enhanced guide, we’ll dive even deeper into the library, drawing from official Android documentation. We’ll cover core concepts with precise explanations, expanded benefits backed by real-world metrics, a thorough analysis of traditional pitfalls (including a bad example), a step-by-step integration tutorial with verbatim code samples, advanced manual initialization techniques (including disabling auto-discovery), performance profiling with Android Studio tools, integration nuances with libraries like WorkManager, common pitfalls with fixes, migration strategies, and emerging best practices. Our goal? Equip you to slash startup times by 30–50% (e.g., from 2 seconds to 800 ms on mid-range devices like Pixel 6 running API 33), while making your codebase more modular, testable, and future-proof. Whether you’re building media apps with push notifications or e-commerce platforms with analytics, this library is a game-changer.</p><h3>What is App Startup? Core Concepts</h3><p>App Startup is a lightweight Jetpack library designed to simplify the initialization of app components during startup. It replaces the inefficient practice of defining multiple ContentProviders for each SDK (which incurs high instantiation costs) with a single, shared InitializationProvider. This enables parallel execution where possible, automatic dependency resolution, and easy discovery via the Android manifest. As per official docs, it’s ideal for both app developers and library authors to declare explicit initialization orders without bloating the main thread.</p><p>Key mechanisms include:</p><ul><li><strong>Initializer&lt;T&gt;</strong>: An abstract class (not just an interface — extends Object) representing each component to initialize. It requires two core methods:</li><li>create(Context context): T — Performs the actual initialization and returns an instance of the component (or Unit for void returns). This runs on the main thread but should avoid blocking I/O; use coroutines for async tasks.</li><li>dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; — Returns a list of dependent Initializer classes. The system topologically sorts these to ensure correct ordering, detecting cycles early (e.g., A depends on B, B on A — throws a RuntimeException).</li><li><strong>InitializationProvider</strong>: A manifest-declared ContentProvider (androidx.startup.InitializationProvider) that acts as the entry point. It scans for Initializers via meta-data tags during app startup (before Application.onCreate()), queues them based on dependencies, and executes in parallel for independent ones. Authorities are set to ${applicationId}.androidx-startup to avoid conflicts.</li><li><strong>Parallel Execution</strong>: Non-dependent Initializers run concurrently, leveraging multi-threading under the hood. Dependent ones wait, but the overall process is non-blocking where possible.</li><li><strong>Automatic Discovery</strong>: No code-based registration — Initializers are auto-detected via &lt;meta-data&gt; entries in the manifest. This keeps your Application class lean.</li><li><strong>AppInitializer</strong>: A singleton utility (AppInitializer.getInstance(context)) for manual control, exposing methods like discoverAndInitialize() (full auto-like run) or initializeComponent(Class&lt;T&gt; clazz) (targeted init, auto-resolving dependencies).</li></ul><p>Version note: As of 1.2.0, it fully supports Kotlin and Java interoperability, with improved lint rules for dependency validation.</p><h3>Why Should You Use It? Detailed Benefits</h3><p>Adopting App Startup isn’t just about speed — it’s about sustainable architecture. Official benchmarks show parallel init reducing startup by up to 40% on devices like Pixel 6 (API 33). For a typical app with 5 SDKs (e.g., Firebase Analytics, Adjust, Netmera for push, logging, and a custom manager), sequential init might take 2 seconds; parallel drops it to 800 ms.</p><p>Expanded benefits:</p><ul><li><strong>Performance Gain</strong>: Shifts from serial to parallel execution, minimizing main-thread blocks. Real tests: Firebase + Crashlytics init drops from 300–500 ms to 150 ms when async-wrapped. Integrates seamlessly with WorkManager for background tasks.</li><li><strong>Dependency Management</strong>: Explicit dependencies() declarations enable topological sorting; cycles are detected at build time via lint, preventing runtime crashes. No more manual if-then chains for ordering.</li><li><strong>Modularity and Testability</strong>: Each Initializer is isolated, injectable (e.g., via Hilt @Inject), and mockable. Unit test a single create() without spinning up the full app — use Robolectric for context simulation.</li><li><strong>Security and Compliance</strong>: Avoids main-thread ANRs (Application Not Responding) by design. Pre-integrated with Jetpack libs like WorkManager (no custom Initializer needed in 1.1.0+), and supports feature flags for conditional init.</li><li><strong>Developer Productivity</strong>: Reduces Application.onCreate() from 200+ lines to ~20. Manifest-driven discovery means no boilerplate registration.</li></ul><p>Drawbacks? Minimal for complex apps, but overkill for tiny ones (&lt;5 components). Initial migration: 1–2 days for large projects, but lint automates much of the heavy lifting. If your app loads Firebase, Adjust, Netmera, or custom managers (e.g., for media playback), it’s essential — especially for cold starts after app kills.</p><h3>Issues with Traditional Approaches: Bad Example Analysis</h3><p>The legacy Application.onCreate() method forces sequential execution on the main thread, amplifying delays from I/O-heavy SDKs (network calls, DB migrations). This spikes ANR risks on low-end devices (e.g., API 24) and buries edge cases like offline init failures. Maintenance? A nightmare inline callbacks, version checks, and service binds create untestable spaghetti code.</p><p>Here’s a summarized bad example from a real-world media app (StartUpAppApplication), highlighting common anti-patterns:</p><pre>// Bad Example: StartUpAppApplication.kt – Sequential Hell in a Media App<br>import com.google.firebase.FirebaseApp<br>import com.adjust.sdk.Adjust<br>import com.adjust.sdk.AdjustConfig<br>import com.adjust.sdk.LogLevel<br>import androidx.multidex.MultiDexApplication<br>import com.netmera.Netmera<br>import com.netmera.NetmeraConfiguration<br>import com.samplapp.common.manager.SharedPrefManager<br>import com.samplapp.common.network.NetworkMonitor<br>import com.samplapp.common.util.AutoUtils<br>import com.samplapp.data.RemoteConfigManager<br>import dagger.hilt.android.HiltAndroidApp<br>import android.content.ComponentName<br>import android.content.Context<br>import android.os.Build<br>import android.util.Log<br><br>@HiltAndroidApp<br>class StartUpAppApplication : MultiDexApplication() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        // 1. Quick but I/O-heavy: AutoUtils (theme/auto-sizing) – 50-100 ms block<br>        AutoUtils.init(this)<br>        // 2. Network-blocking: Firebase (Analytics + Crashlytics) – 300-500 ms!<br>        FirebaseApp.initializeApp(this)<br>        // 3. Conditional sequential: NetworkMonitor – waits for Firebase, adds 100 ms<br>        NetworkMonitor.initialize(this)<br>        // 4. Memory-intensive: SharedPrefs (user prefs, themes) – 200 ms<br>        SharedPrefManager.init(this)<br>        // 5. Callback-heavy: Netmera (push notifications) – 300-600 ms, depends on Firebase<br>        val configBuilder = NetmeraConfiguration.Builder()<br>            .apiKey(&quot;SAMPLE_API_KEY&quot;)<br>            .firebaseSenderId(&quot;SAMPLE_FCM_ID&quot;)<br>            .logging(true)<br>        Netmera.init(configBuilder.build(this))<br>        Netmera.enablePopupPresentation()<br>        // 6. Service bind: MusicService (foreground playback) – 150 ms<br>        val serviceComponent = ComponentName(this, MusicService::class.java)<br>        MusicServiceConnectionManager.getInstance().init(this, serviceComponent)<br>        // 7. Analytics: Adjust (event tracking) – 200 ms, global lifecycle attach<br>        initAdjust()<br>        // 8. Extra block: Remote Config fetch – 500 ms+ network wait<br>        RemoteConfigManager.fetchAndActivate()<br>    }<br><br>    private fun initAdjust() {<br>        val adjustConfig = AdjustConfig(this, &quot;SAMPLE_APP_TOKEN&quot;, AdjustConfig.ENVIRONMENT_PRODUCTION)<br>        adjustConfig.setLogLevel(LogLevel.VERBOSE)<br>        Adjust.initSdk(adjustConfig)<br>    }<br>    // ... (attachBaseContext for MultiDex, more callbacks – total: 300+ lines of bloat!)<br>}</pre><p><strong>Why a Disaster?</strong></p><ul><li><strong>Sequential Blocking</strong>: Slow Firebase (bad network) delays Netmera by 500 ms — total cold start: 1.5–2.5 seconds. Parallelism? Absent.</li><li><strong>Main Thread Risks</strong>: Sync network/DB calls invite ANRs; low-end devices crash under load.</li><li><strong>Complexity Explosion</strong>: Version guards, inline configs, and callbacks resist refactoring. Testing? Mock the entire onCreate() — impossible.</li><li><strong>Edge Case Blind Spots</strong>: Cold starts miss early push messages; offline inits fail silently.</li><li><strong>Scalability Fail</strong>: Adding one SDK bloats everything; no dependency visualization.</li></ul><p>Result: 20% abandonment (Google Play metrics), plus poor Lighthouse scores in Play Console.</p><h3>Correct Usage: App Startup Integration Step by Step</h3><p>Integration is straightforward: 4 steps, ~30 minutes for basics. Add to build.gradle (app):</p><pre>implementation(&quot;androidx.startup:startup-runtime:1.2.0&quot;)</pre><p>Sync and build.</p><h3>Step 1: Create Initializer Classes</h3><p>Encapsulate each component. Use create() for init, dependencies() for ordering. Official examples emphasize returning the component instance for downstream use. Here’s an expanded set for SampleApp, including async wrappers and Hilt compatibility:</p><pre>// FirebaseInitializer.kt – Analytics, Crashlytics, Remote Config (Independent, Early Run)<br>import androidx.startup.Initializer<br>import com.google.firebase.FirebaseApp<br>import com.google.firebase.crashlytics.FirebaseCrashlytics<br>import com.google.firebase.analytics.FirebaseAnalytics<br>import kotlinx.coroutines.CoroutineScope<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.launch<br>import javax.inject.Inject<br><br>class FirebaseInitializer @Inject constructor() : Initializer&lt;Unit&gt; {  // Injectable for testing<br>    override fun create(context: Context): Unit {<br>        FirebaseApp.initializeApp(context)<br>        FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true)<br>        FirebaseAnalytics.getInstance(context)<br>        // Async fetch to avoid block (best practice)<br>        CoroutineScope(Dispatchers.IO).launch {<br>            RemoteConfigManager.fetchAndActivate()<br>        }<br>        return Unit<br>    }<br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; = emptyList()  // No deps<br>}<br><br>// NetmeraInitializer.kt – Push SDK (Depends on Firebase for FCM)<br>import com.netmera.Netmera<br>import com.netmera.NetmeraConfiguration<br><br>class NetmeraInitializer : Initializer&lt;Unit&gt; {<br>    override fun create(context: Context): Unit {<br>        val configBuilder = NetmeraConfiguration.Builder()<br>            .apiKey(&quot;SAMPLE_API_KEY&quot;)<br>            .firebaseSenderId(&quot;SAMPLE_FCM_ID&quot;)<br>            .logging(true)<br>        Netmera.init(configBuilder.build(context))<br>        Netmera.enablePopupPresentation()<br>        return Unit<br>    }<br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; = <br>        listOf(FirebaseInitializer::class.java)  // Ensures FCM ready<br>}<br><br>// AdjustInitializer.kt – Analytics (Depends on Firebase)<br>import com.adjust.sdk.Adjust<br>import com.adjust.sdk.AdjustConfig<br>import com.adjust.sdk.LogLevel<br><br>class AdjustInitializer : Initializer&lt;Unit&gt; {<br>    override fun create(context: Context): Unit {<br>        val adjustConfig = AdjustConfig(context, &quot;SAMPLE_APP_TOKEN&quot;, AdjustConfig.ENVIRONMENT_PRODUCTION)<br>        adjustConfig.setLogLevel(LogLevel.VERBOSE)<br>        Adjust.initSdk(adjustConfig)<br>        return Unit<br>    }<br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; = <br>        listOf(FirebaseInitializer::class.java)  // For deferred deep links<br>}<br><br>// SharedPrefInitializer.kt – User Prefs (No Deps)<br>class SharedPrefInitializer : Initializer&lt;Unit&gt; {<br>    override fun create(context: Context): Unit {<br>        SharedPrefManager.init(context)<br>        return Unit<br>    }<br>    override fun dependencies(): emptyList()<br>}<br><br>// WorkManagerInitializer.kt – Background Tasks (Official Integration Example)<br>import androidx.startup.Initializer<br>import androidx.work.Configuration<br>import androidx.work.WorkManager<br><br>class WorkManagerInitializer : Initializer&lt;WorkManager&gt; {  // Returns WorkManager instance<br>    override fun create(context: Context): WorkManager {<br>        val config = Configuration.Builder()<br>            .setMinimumLoggingLevel(Log.DEBUG)<br>            .build()<br>        WorkManager.initialize(context, config)<br>        return WorkManager.getInstance(context)<br>    }<br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; = emptyList()<br>}<br><br>// AutoUtilsInitializer.kt – Theme/Auto-Sizing (Quick, No Deps)<br>class AutoUtilsInitializer : Initializer&lt;Unit&gt; {<br>    override fun create(context: Context): Unit {<br>        AutoUtils.init(context)<br>        return Unit<br>    }<br>    override fun dependencies(): emptyList()<br>}<br><br>// NetworkMonitorInitializer.kt – Connectivity (Post-Android N)<br>class NetworkMonitorInitializer : Initializer&lt;Unit&gt; {<br>    override fun create(context: Context): Unit {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>            NetworkMonitor.initialize(context)<br>        }<br>        return Unit<br>    }<br>    override fun dependencies(): emptyList()<br>}<br><br>// ExampleLoggerInitializer.kt – Custom Logger (Depends on WorkManager, Official Pattern)<br>class ExampleLoggerInitializer : Initializer&lt;ExampleLogger&gt; {<br>    override fun create(context: Context): ExampleLogger {<br>        // Safe access post-dependency<br>        return ExampleLogger(WorkManager.getInstance(context))<br>    }<br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; = <br>        listOf(WorkManagerInitializer::class.java)<br>}</pre><p>Tips: Wrap network ops in CoroutineScope(Dispatchers.IO). For Hilt, annotate with @Inject. Keep create() lightweight —</p><h3>Step 2: Clean Up the Application Class</h3><p>Minimalism is key — let App Startup handle 90%:</p><pre>@HiltAndroidApp<br>class StartUpAppApplication : MultiDexApplication() {<br>    override fun onCreate() {<br>        super.onCreate()<br><br>        // No need to initialize here anymore,<br>        // thanks to the Initializers we created,<br>        // all startup processes are now handled automatically.<br><br>    }<br>    override fun attachBaseContext(base: Context?) {<br>        super.attachBaseContext(base)<br>        MultiDex.install(this)<br>    }<br>}</pre><h3>Step 3: Update AndroidManifest.xml</h3><p>Declare the provider and meta-data for discovery. Use tools:node=”merge” for library conflicts:</p><pre>&lt;provider<br>    android:name=&quot;androidx.startup.InitializationProvider&quot;<br>    android:authorities=&quot;${applicationId}.androidx-startup&quot;<br>    android:exported=&quot;false&quot;<br>    tools:node=&quot;merge&quot;&gt;<br>    &lt;!-- Auto-discover all Initializers --&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.FirebaseInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.NetmeraInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.AdjustInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.SharedPrefInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.WorkManagerInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.AutoUtilsInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.NetworkMonitorInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>    &lt;meta-data android:name=&quot;com.startupapp.ExampleLoggerInitializer&quot; android:value=&quot;androidx.startup&quot; /&gt;<br>&lt;/provider&gt;</pre><p>Note: WorkManager doesn’t need explicit meta-data if depended on — it’s pulled in automatically.</p><h3>Step 4: Test and Validation</h3><ul><li><strong>Lint Checks</strong>: Run ./gradlew :app:lintDebug — App Startup’s built-in rules flag cycles, missing deps, and manifest errors (e.g., “Cyclic dependency detected”).</li><li><strong>Startup Profiler</strong>: See below for details.</li><li><strong>Manual Trigger</strong>: In debug, AppInitializer.getInstance(context).discoverAndInitialize() for on-demand runs.</li><li><strong>Unit Tests</strong>: Mock Context in create(); assert deps with verify in Mockito.</li></ul><h3>Manual Initialization: When and How to Use It?</h3><p>Auto-discovery is default, but manual via AppInitializer offers fine-grained control — crucial for conditional or lazy loading. Official docs stress: Manual resolves deps automatically but skips discovery overhead (~10 ms savings).</p><h3>Disabling Auto-Init</h3><p>To prevent unwanted runs:</p><ul><li><strong>Single Component</strong>: Remove its &lt;meta-data&gt; or add tools:node=”remove”:</li></ul><pre>&lt;meta-data android:name=&quot;com.samplapp.NetmeraInitializer&quot; tools:node=&quot;remove&quot; /&gt;</pre><ul><li><strong>All Auto</strong>: Remove the entire &lt;provider&gt; with tools:node=”remove”.</li></ul><p>This avoids instantiation costs for unused components (e.g., pro-only analytics).</p><h3>Performing Manual Init</h3><p>Access: val initializer = AppInitializer.getInstance(context).</p><ul><li><strong>Full Discovery</strong>: initializer.discoverAndInitialize() — Mimics auto, but callable anytime.</li><li><strong>Targeted</strong>: initializer.initializeComponent(MyInitializer::class.java) — Auto-pulls deps (e.g., calling Netmera pulls Firebase).</li></ul><p>Example in SplashActivity (lazy for flavors):</p><pre>// SplashActivity.kt – Conditional/Lazy Init<br>class SplashActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        // Pro flavor only: Manual Netmera<br>        if (BuildConfig.FLAVOR == &quot;pro&quot;) {<br>            AppInitializer.getInstance(this).initializeComponent(NetmeraInitializer::class.java)<br>        }<br>        // Async Firebase (e.g., post-splash)<br>        lifecycleScope.launch {<br>            AppInitializer.getInstance(this@SplashActivity).initializeComponent(FirebaseInitializer::class.java)<br>        }<br>    }<br>}</pre><p><strong>When to Use</strong>:</p><ul><li><strong>Conditional</strong>: Feature flags (debug logging only; skip analytics offline).</li><li><strong>Lazy</strong>: Delay heavy SDKs (push after login) for sub-500 ms cold starts.</li><li><strong>Modular</strong>: Dynamic feature modules — init on load to avoid main APK bloat.</li><li><strong>Testing/Debug</strong>: Mock and trigger in Robolectric; correlate logs with timelines.</li><li><strong>Hybrid</strong>: Auto for essentials (SharedPrefs), manual for optionals (RemoteConfig if online).</li></ul><p><strong>Avoid When</strong>: Simple apps — auto suffices. Manual breaks auto-dep resolution if overused; always check isInitialized() for skips in warm starts.</p><p><strong>Warning</strong>: Post-manual, no re-init guarantees — use flags. Performance edge: Manual &gt; Auto (no manifest scan).</p><h3>Testing with Profiler: Measure and Optimize Startup Performance</h3><p>Android Studio’s Profiler dissects startup with us precision via the “App Startup” tab — auto-activates with the library. Focus on cold (force-stop/relaunch) vs. warm (background/foreground) starts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kpzo-dPk0-n-hgK675NvFA.png" /><figcaption>Profiler</figcaption></figure><h3>Step 1: Setup</h3><ul><li>Device/Emu: API 30+, USB debug on. Wipe data for cold.</li><li>Build: Debug mode (obfuscation skews timings).</li><li>Profiler: View &gt; Tool Windows &gt; Profiler &gt; Record.</li></ul><h3>Step 2: Capture and Analyze</h3><ol><li>Launch app — Profiler grabs first 5–10s.</li><li>Sessions tab &gt; New session &gt; App Startup (left menu).</li><li><strong>Timeline</strong>: X: ms; Y: Initializers. Blues: parallel; Reds: blocks; Greens: done.</li></ol><ul><li>Metrics: Total &lt;500 ms goal; Per-init (e.g., Firebase 200 ms? Async it).</li><li>Graph: Deps visualized — red for cycles.</li></ul><p>4. Drill-Down: Click for call stacks; CPU tab for threads; Memory for spikes.</p><h3>Step 3: Comparative Scenarios</h3><ul><li><strong>Before/After</strong>: Sequential: ~2s bars stacked; App Startup: Overlapping ~800 ms.</li><li><strong>Variants</strong>: Warm (check skips via isInitialized() impl.); Network latency (Emu Controls &gt; Cellular); Low-end (API 24 emu).</li><li><strong>StrictMode</strong>: StrictMode.setThreadPolicy(…) in onCreate() — flags leaks in Logcat.</li></ul><h3>Step 4: Optimize and Report</h3><ul><li><strong>Fixes</strong>: Async create(); Trim deps for more parallelism.</li><li><strong>Exports</strong>: JSON/trace for CI (GitHub Actions baselines).</li><li><strong>Advanced</strong>: androidx.benchmark for automated StartupTimingMetric; Log timestamps in create() for correlation.</li><li><strong>Limits</strong>: Profiler overhead ~10–20 ms; Prod: Firebase Perf or custom traces.</li></ul><p>In SampleApp, Firebase dropped 500→150 ms — user retention up 15%!</p><h3>Performance Tips and Common Pitfalls</h3><p><strong>Tips</strong> :</p><ul><li><strong>Async Everything</strong>: Dispatchers.IO for network/DB; coroutines in create().</li><li><strong>Minimal Deps</strong>: Excess ordering kills parallelism — lint validates.</li><li><strong>Profiling Duo</strong>: StrictMode + Benchmark lib for leaks/macros.</li><li><strong>Manifest Magic</strong>: tools:node=”merge/remove” resolves lib conflicts.</li><li><strong>Warm Start Hooks</strong>: Impl isInitialized() to skip re-runs.</li></ul><p><strong>Pitfalls &amp; Fixes</strong>:</p><ul><li><strong>Cyclic Deps</strong>: Lint error — “Cyclic dependency detected.” Fix: Reorder or split.</li><li><strong>Manifest Miss</strong>: No run → Logcat “Unknown initializer.” Add meta-data.</li><li><strong>Context Leaks</strong>: No static holds — pass fresh Context.</li><li><strong>Hilt Conflicts</strong>: Use @Inject in Initializers; compat with 1.2.0+.</li><li><strong>Version Mismatch</strong>: WorkManager auto in 1.1.0+; manual otherwise.</li><li><strong>Over-Manual</strong>: Forgets deps — use initializeComponent always.</li></ul><h3>Migration Strategy: Step-by-Step Transition</h3><ol><li><strong>Audit</strong>: Scan onCreate() — list components, estimate times (Profiler baseline).</li><li><strong>Prototype</strong>: Migrate 2–3 (e.g., Firebase, WorkManager) — test lint.</li><li><strong>Incremental (1 Week)</strong>: Critical SDKs first; measure per-sprint.</li><li><strong>Full</strong>: Extract callbacks; update manifest; disable legacy providers.</li><li><strong>CI/CD</strong>: Mandate ./gradlew lint; benchmark gates in PRs.</li></ol><p>Tools: Official migration guide links to WorkManager/DataStore docs for parallels.</p><h3>Get Future-Ready with App Startup</h3><p>App Startup transforms Android startups from bottlenecks to breezes: fast, modular, and lint-safe. Ditch the sequential disasters; embrace Initializers for parallelism and manual flexibility. In push/media apps like StartUpApp, gains are transformative — 40% faster, testable code.</p><p>Dive deeper: <a href="https://developer.android.com/topic/libraries/app-startup">Official Docs</a>.</p><p>Refactored yet? Drop your profiler wins or manual tricks below! If you’d like to connect, discuss implementations, or share your experiences, feel free to reach out via LinkedIn. <a href="https://www.linkedin.com/in/hakanncevikk/">Hakan Çevik</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088715f81116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Audio Focus in Android]]></title>
            <link>https://medium.com/@hakanxcevik7/managing-audio-focus-in-android-41ea61731473?source=rss-5902460faa66------2</link>
            <guid isPermaLink="false">https://medium.com/p/41ea61731473</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[focus]]></category>
            <dc:creator><![CDATA[Hakan Cevik]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 07:58:59 GMT</pubDate>
            <atom:updated>2025-09-26T08:20:45.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42ZHgNXJ6AJtx0GUhdvpOA.png" /></figure><p>In Android, managing audio playback correctly requires more than simply starting a MediaPlayer. One of the essential components for building a robust audio application is <strong>Audio Focus</strong>. Proper management ensures that applications coexist smoothly with other audio sources and provide a consistent user experience.</p><p>For example, if an application is playing music and another app initiates audio playback or a phone call occurs, failure to handle audio focus appropriately may result in overlapping audio streams, creating an undesirable user experience.</p><p>For this reason, audio focus is typically managed within a <strong>Service</strong>, rather than a ViewModel. This approach allows audio playback to continue independently of the UI lifecycle.</p><h3>Audio Focus: Purpose and Application</h3><p><strong>Audio Focus</strong> is Android’s mechanism for determining which application should control audio output at a given time. It enables the system to notify applications of focus changes so they can respond appropriately by pausing, ducking, or resuming playback.</p><p>Audio focus management is particularly relevant in the following scenarios:</p><ul><li><strong>Music and podcast applications:</strong> Temporary audio interruptions, such as navigation directions or notifications, require pausing or reducing playback volume.</li><li><strong>VoIP and call applications:</strong> Incoming calls require the suspension of media playback.</li><li><strong>Games:</strong> Game audio may need to adjust when system sounds or other applications produce audio.</li><li><strong>Navigation and TTS applications:</strong> Short audio prompts may require temporary focus requests.</li></ul><p>The correct handling of audio focus ensures a seamless user experience, even when multiple applications are producing audio simultaneously.</p><h3>Audio Focus Events</h3><p>Android provides several focus change events:</p><ul><li><strong>AUDIOFOCUS_GAIN</strong>: The application has gained audio focus and can resume playback or restore volume.</li><li><strong>AUDIOFOCUS_LOSS</strong>: The application has permanently lost focus and should stop playback and release resources.</li><li><strong>AUDIOFOCUS_LOSS_TRANSIENT</strong>: Temporary loss; the application should pause playback temporarily.</li><li><strong>AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK</strong>: Temporary loss where playback may continue at a reduced volume (“ducking”).</li></ul><p>Applications can handle these events to ensure proper interaction with other audio sources and system notifications.</p><h3>Implementing a MusicService with Audio Focus</h3><p>Here’s how I structure my service. I use a MediaPlayer for simplicity, but the same logic works with ExoPlayer or other audio engines.</p><pre>class MusicService : Service(), AudioManager.OnAudioFocusChangeListener {<br><br>    private lateinit var audioManager: AudioManager<br>    private var mediaPlayer: MediaPlayer? = null<br>    private var hasAudioFocus = false<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager<br>        mediaPlayer = MediaPlayer.create(this, R.raw.sample_music)<br>        mediaPlayer?.isLooping = true<br>    }<br><br>    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>        if (requestAudioFocus()) {<br>            startPlayback()<br>        }<br>        return START_STICKY<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        stopPlayback()<br>        abandonAudioFocus()<br>        mediaPlayer?.release()<br>        mediaPlayer = null<br>    }<br><br>    override fun onBind(intent: Intent?): IBinder? = null</pre><h3>Handling Audio Focus Changes</h3><pre>    override fun onAudioFocusChange(focusChange: Int) {<br>        when (focusChange) {<br>            AudioManager.AUDIOFOCUS_GAIN -&gt; {<br>                hasAudioFocus = true<br>                resumePlayback()<br>            }<br>            AudioManager.AUDIOFOCUS_LOSS -&gt; {<br>                hasAudioFocus = false<br>                stopPlayback()<br>            }<br>            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -&gt; {<br>                hasAudioFocus = false<br>                pausePlayback()<br>            }<br>            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -&gt; {<br>                mediaPlayer?.setVolume(0.2f, 0.2f)<br>            }<br>        }<br>    }</pre><h3>Requesting and Abandoning Focus</h3><pre>    private fun requestAudioFocus(): Boolean {<br>        val result = audioManager.requestAudioFocus(<br>            this,<br>            AudioManager.STREAM_MUSIC,<br>            AudioManager.AUDIOFOCUS_GAIN<br>        )<br>        hasAudioFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED<br>        return hasAudioFocus<br>    }<br><br>    private fun abandonAudioFocus() {<br>        audioManager.abandonAudioFocus(this)<br>        hasAudioFocus = false<br>    }</pre><h3>Playback Controls</h3><pre>    private fun startPlayback() {<br>        mediaPlayer?.start()<br>    }<br><br>    private fun pausePlayback() {<br>        mediaPlayer?.pause()<br>    }<br><br>    private fun resumePlayback() {<br>        if (!(mediaPlayer?.isPlaying ?: false)) {<br>            mediaPlayer?.start()<br>            mediaPlayer?.setVolume(1.0f, 1.0f)<br>        }<br>    }<br><br>    private fun stopPlayback() {<br>        mediaPlayer?.stop()<br>        mediaPlayer?.prepareAsync()<br>    }<br>}</pre><h3>Summary</h3><ul><li>Audio focus ensures that applications interact harmoniously with other audio sources and system events.</li><li>Handling audio focus within a Service allows playback to continue independently of the UI lifecycle.</li><li>Applications should respond appropriately to focus gain, loss, transient loss, and ducking events.</li><li>Requesting audio focus before starting playback and abandoning it when stopping is essential for proper behavior.</li><li>Volume adjustments during temporary focus loss improve the user experience in multi-app environments.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41ea61731473" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Android Auto Media App: A Deep Dive into Music Streaming Integration]]></title>
            <link>https://medium.com/@hakanxcevik7/building-an-android-auto-media-app-a-deep-dive-into-music-streaming-integration-c239d6a2c494?source=rss-5902460faa66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c239d6a2c494</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-auto]]></category>
            <category><![CDATA[streaming-music-service]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Hakan Cevik]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 18:04:08 GMT</pubDate>
            <atom:updated>2025-08-25T18:04:08.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jKtEjqk2UXQ5haJy.png" /></figure><p>Hello fellow developers and technology enthusiasts,</p><p>If you’ve ever wanted to bring your music streaming application to the car dashboard, this article is for you. Over the past months, I have been working on building a complete media application — covering artists, albums, playlists, and tracks — and ensuring that it integrates seamlessly with <strong>Android Auto</strong>. Throughout this journey, I’ve encountered valuable lessons, challenges, and solutions that I would like to share with you. My goal is to help you implement Android Auto support in your own applications with clarity and confidence.</p><p>As of <strong>August 2025</strong>, Android Auto has become a significant platform, available in more than <strong>200 million compatible vehicles</strong> worldwide. It transforms smartphones into a driver-friendly hub for navigation, communication, and, most importantly, media playback. Imagine being on the highway and saying: <em>“Hey Google, play my evening playlist.”</em> Your application responds instantly, providing music without unnecessary distraction. This is the type of seamless user experience that Android Auto enables — and that developers like us aim to deliver.</p><p>In this article, I will explain how I integrated Android Auto into my application, focusing on components such as <strong>MediaBrowserServiceCompat</strong>, <strong>MediaSessionCompat</strong>, and the steps required to make a media library both browsable and playable in the car environment. While my application focuses on music streaming, the same concepts can be applied to podcasts, audiobooks, or any other form of audio content.</p><h3>Why Android Auto? The Key Motivations</h3><p>My interest in Android Auto integration began the moment I experienced a well-designed music application on a car dashboard. The large album artwork, voice commands, and driving-optimized controls immediately showed me the value of bringing applications into this ecosystem.</p><p>Here are the main reasons Android Auto integration should not be overlooked:</p><ul><li><strong>User Engagement:</strong> People spend a significant amount of time in their cars, making in-vehicle apps highly relevant.</li><li><strong>Safety:</strong> Voice control and simplified UI reduce driver distraction, contributing to safer usage.</li><li><strong>Widespread Adoption:</strong> From entry-level vehicles to premium brands, Android Auto is broadly supported.</li><li><strong>Competitive Advantage:</strong> Applications that omit Android Auto support risk losing users to alternatives that provide it.</li></ul><p>Of course, integration is not a matter of copying and pasting code. It requires a solid understanding of the <strong>Media Browser API</strong>, <strong>session management</strong>, audio focus handling, and lifecycle management. For example, the app must gracefully handle cases such as a user unplugging the device mid-playback.</p><p>Getting started: Tools and Setup:</p><h3>Dependencies</h3><ul><li>androidx.media:media:1.2.1 → Media Browser and Media Session APIs</li><li>com.github.bumptech.glide:glide:4.16.0 → Efficient album art loading</li><li>dagger.hilt.android:2.51 → Dependency injection for clean architecture</li><li>com.google.android.exoplayer:exoplayer:2.19.1 → Reliable media playback engine</li></ul><h3>Testing Environment</h3><ul><li><strong>Android Auto Desktop Head Unit (DHU):</strong><br> For emulator-based testing, Google provides the Desktop Head Unit (DHU) tool. This simulates the Android Auto environment on your development machine, allowing you to test media playback without needing a physical car.</li><li>To run DHU, connect your device via USB, navigate to the DHU installation directory, and execute the following command (adjust the path according to your SDK installation):</li></ul><pre>/Users/your-username/Library/Android/sdk/extras/google/auto/desktop-head-unit -u</pre><ul><li>The -u flag tells DHU to connect to your phone over USB. Once running, DHU will mirror how Android Auto would render your application on a car’s dashboard.</li><li>Note: Replace /Users/your-username/Library/Android/sdk/ with the correct SDK path on your system. For example, on Windows this might be C:\Users\&lt;username&gt;\AppData\Local\Android\Sdk\extras\google\auto\desktop-head-unit.exe.</li><li><strong>Physical Vehicle Testing:</strong><br> While DHU is great for rapid iteration, I also recommend testing in a real vehicle to validate behavior under real-world conditions (e.g., connection stability, audio focus changes, and unplug scenarios).</li></ul><h3>Manifest Configuration</h3><p>To make the app discoverable by Android Auto, a <strong>MediaBrowserServiceCompat</strong> must be declared in the manifest. This is the entry point that informs Android Auto that your application supports media playback in the car.</p><p>In your AndroidManifest.xml, add:</p><pre>&lt;service<br>android:name=&quot;.media.MusicService&quot;<br>android:exported=&quot;true&quot;<br>android:foregroundServiceType=&quot;mediaPlayback&quot;&gt;<br>&lt;intent-filter&gt;<br>&lt;action android:name=&quot;android.media.browse.MediaBrowserService&quot; /&gt;<br>&lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><p>This says, “Hey, Android Auto, come talk to my service!”</p><h3>How Android Auto Works: The Big Picture</h3><p>Android Auto is like a translator between your phone and the car’s screen. It projects a simplified UI — big buttons, bold text, minimal clutter — so drivers stay focused. You connect via USB (wired) or Wi-Fi/Bluetooth (wireless), and the car’s display becomes a portal to your app.</p><p>For music apps, here’s the flow:</p><ol><li><strong>Discovery</strong>: Auto scans for apps with a MediaBrowserService.</li><li><strong>Connection</strong>: It hooks up using MediaBrowserCompat, asking for your content “root.”</li><li><strong>Browsing</strong>: Users navigate a tree (e.g., Artists → Albums → Tracks) via the car’s UI.</li><li><strong>Playback</strong>: Taps or voice commands trigger play, pause, skip, etc., through a media session.</li><li><strong>Notifications</strong>: Show up on the lock screen and car display, mirroring controls.</li><li><strong>Voice Magic</strong>: Google Assistant handles “Play The Beatles” or “Next track.”</li></ol><p>My app’s structure is simple but powerful:</p><ul><li><strong>Root</strong>: Top-level categories like “Artists,” “Albums,” “Playlists.”</li><li><strong>Artists</strong>: List of artists, each leading to their albums.</li><li><strong>Albums/Playlists</strong>: Lists of tracks, ready to play.</li></ul><p>This setup feels natural in a car — quick to navigate, easy to voice-control.</p><h3>Building the Core: My MusicService Class</h3><p>Alright, let’s get to the fun part: coding the MusicService. This is the heart of the app, a MediaBrowserServiceCompat that serves content and handles playback. I made it a LifecycleOwner for clean coroutine handling and added audio focus to play nice with other apps.</p><h3>The Setup: Imports and Class</h3><pre>package com.agile.musicapp.media<br><br>import android.app.Notification<br>import android.app.NotificationChannel<br>import android.app.NotificationManager<br>import android.app.PendingIntent<br>import android.content.Intent<br>import android.media.AudioManager<br>import android.os.Build<br>import android.os.Bundle<br>import android.os.SystemClock<br>import android.support.v4.media.MediaBrowserCompat<br>import android.support.v4.media.MediaDescriptionCompat<br>import android.support.v4.media.MediaMetadataCompat<br>import android.support.v4.media.session.MediaSessionCompat<br>import android.support.v4.media.session.PlaybackStateCompat<br>import androidx.core.app.NotificationCompat<br>import androidx.core.app.ServiceCompat<br>import androidx.lifecycle.Lifecycle<br>import androidx.lifecycle.LifecycleOwner<br>import androidx.lifecycle.LifecycleRegistry<br>import androidx.media.session.MediaButtonReceiver<br>import com.bumptech.glide.Glide<br>import com.google.android.exoplayer2.ExoPlayer<br>import dagger.hilt.android.AndroidEntryPoint<br>import javax.inject.Inject<br><br>@AndroidEntryPoint<br>class MusicService : MediaBrowserServiceCompat(), LifecycleOwner, AudioManager.OnAudioFocusChangeListener {<br><br>    private val CHANNEL_ID = &quot;music_channel&quot;<br>    private val NOTIFICATION_ID = 1<br><br>    private var mediaSession: MediaSessionCompat? = null<br>    private val lifecycleRegistry = LifecycleRegistry(this)<br><br>    @Inject lateinit var audioManager: AudioManager<br>    @Inject lateinit var musicUseCase: MusicUseCase  // Fetches artists, albums, tracks<br><br>    private var player: ExoPlayer? = null<br>    private var currentTrack: Track? = null<br>    private var hasAudioFocus = false<br>    private var isForeground = false<br><br>    private var playAction: NotificationCompat.Action? = null<br>    private var pauseAction: NotificationCompat.Action? = null<br>    private var nextAction: NotificationCompat.Action? = null<br>    private var prevAction: NotificationCompat.Action? = null<br>}</pre><ul><li><strong>LifecycleOwner</strong>: Lets me tie coroutines to the service’s life, so no memory leaks.</li><li><strong>Audio Focus</strong>: Ensures we pause if a call comes in.</li><li><strong>Hilt</strong>: Injects dependencies like MusicUseCase for data fetching.</li><li><strong>ExoPlayer</strong>: My go-to for streaming. You could swap it for your own player.</li></ul><h3>Kicking Things Off: onCreate</h3><p>This is where I set up the media session, player, and notifications.</p><pre>override fun onCreate() {<br>    super.onCreate()<br>    lifecycleRegistry.currentState = Lifecycle.State.CREATED<br>    lifecycleRegistry.currentState = Lifecycle.State.STARTED<br><br>    mediaSession = MediaSessionCompat(this, &quot;MusicService&quot;).apply {<br>        setCallback(MediaSessionCallback())<br>        setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)<br>        isActive = true<br>    }<br>    sessionToken = mediaSession?.sessionToken<br><br>    player = ExoPlayer.Builder(this).build()<br>    player?.addListener(PlayerListener())  // For playback state changes<br><br>    createNotificationChannel()<br>    requestAudioFocus()<br><br>    MusicConnectionManager.instance.playbackCommand.observe(this) { command -&gt;<br>        handlePlaybackCommand(command)<br>    }<br>}</pre><ul><li><strong>Media Session</strong>: I set flags for media buttons and transport controls so Auto, notifications, and Bluetooth devices can control playback. Activating it makes it visible to the system.</li><li><strong>Session Token</strong>: Auto needs this to connect.</li><li><strong>Player</strong>: Initialize ExoPlayer for streaming.</li><li><strong>Notifications</strong>: Set up a channel for Oreo+ (no sound/vibration for media).</li><li><strong>Commands</strong>: Listen for play/pause commands from the app’s UI via a shared manager.</li></ul><h3>Handling Audio Focus: Playing Nice with Others</h3><p>I learned the hard way that audio focus is non-negotiable. If your app blasts music during a phone call, users will hate you.</p><pre>private fun requestAudioFocus(): Boolean {<br>    if (hasAudioFocus) return true<br>    val result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)<br>    hasAudioFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED<br>    return hasAudioFocus<br>}<br><br>override fun onAudioFocusChange(focusChange: Int) {<br>    when (focusChange) {<br>        AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -&gt; {<br>            hasAudioFocus = false<br>            pausePlayback()<br>        }<br>        AudioManager.AUDIOFOCUS_GAIN -&gt; {<br>            hasAudioFocus = true<br>            resumePlayback()<br>        }<br>    }<br>}<br><br>private fun abandonAudioFocus() {<br>    audioManager.abandonAudioFocus(this)<br>    hasAudioFocus = false<br>}</pre><ul><li><strong>Request</strong>: Grab focus before playing. If denied, I queue the action.</li><li><strong>Change Listener</strong>: Pause on loss (e.g., call), resume on gain. I could duck volume for transient losses (like navigation prompts), but pausing felt safer.</li><li><strong>Abandon</strong>: Clean up when stopping.</li></ul><h3>Browsing Music: onGetRoot and onLoadChildren</h3><p>Here’s where the fun begins — letting users browse your music library like flipping through a record store in their car.</p><h3>onGetRoot: The Front Door</h3><p>This method is Android Auto’s first stop. It decides if the client (e.g., Auto) can connect and what the “root” of the content tree looks like.</p><pre>override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? {<br>    // Optional: Only allow Android Auto<br>    if (!clientPackageName.contains(&quot;com.google.android.projection&quot;)) {<br>        return null  // Sorry, not you!<br>    }<br><br>    val extras = Bundle().apply {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>            putInt(&quot;android.media.browse.CONTENT_STYLE_BROWSABLE_HINT&quot;, 2) // Grid style<br>            putInt(&quot;android.media.browse.CONTENT_STYLE_PLAYABLE_HINT&quot;, 2) // Grid style<br>        } else {<br>            putInt(&quot;android.media.browse.CONTENT_STYLE_BROWSABLE_HINT&quot;, 1) // List style<br>            putInt(&quot;android.media.browse.CONTENT_STYLE_PLAYABLE_HINT&quot;, 1) // List style<br>        }<br>    }<br>    return BrowserRoot(&quot;root&quot;, extras)<br>}</pre><figure><img alt="Grid style" src="https://cdn-images-1.medium.com/max/1024/0*8GFm3Qhl9ByUMIU7.png" /><figcaption>Grid items prioritize images over titles and metadata.</figcaption></figure><ul><li><strong>What’s Happening</strong>: I check if it’s Android Auto (security first!). Then, I set up a Bundle with style hints — grids (2) for newer devices (more visual, shows album art), lists (1) for older ones (text-heavy, less memory). The BrowserRoot says, “Start at ‘root’ for content.”</li><li><strong>Why It Matters</strong>: This is the handshake. Without it, Auto can’t see your app. Style hints make the UI car-friendly — grids are easier to scan while driving.</li><li><strong>Pro Tip</strong>: You could customize the root per user (e.g., “root_user123” for personalized playlists), but “root” keeps it simple.</li><li><strong>Important Note</strong>: If you return null, the connection fails. I forgot this once and spent hours debugging!</li></ul><h3>onLoadChildren: Building the Music Library</h3><p>This method populates the content tree. Android Auto calls it with a parentId (like “root” or “ALBUM_123”) to get items to display. It’s async, so I detach the result and fetch data in the background.</p><pre>override fun onLoadChildren(<br>    parentId: String,<br>    result: Result&lt;MutableList&lt;MediaBrowserCompat.MediaItem&gt;&gt;<br>) {<br>    result.detach()<br>    val helper = MusicLifecycleHelper.getInstance(this, musicUseCase)<br><br>    when (parentId) {<br>        &quot;root&quot; -&gt; result.sendResult(getRootCategories())<br>        &quot;ARTISTS&quot; -&gt; helper.fetchArtists { artists -&gt;<br>            result.sendResult(artists.map { createArtistItem(it) }.toMutableList())<br>        }<br>        &quot;ALBUMS&quot; -&gt; helper.fetchAlbums { albums -&gt;<br>            result.sendResult(albums.map { createAlbumItem(it) }.toMutableList())<br>        }<br>        &quot;PLAYLISTS&quot; -&gt; helper.fetchPlaylists { playlists -&gt;<br>            result.sendResult(playlists.map { createPlaylistItem(it) }.toMutableList())<br>        }<br>        else -&gt; when {<br>            parentId.startsWith(&quot;ALBUM_&quot;) -&gt; {<br>                val albumId = parentId.substringAfter(&quot;ALBUM_&quot;)<br>                helper.fetchTracksForAlbum(albumId) { tracks -&gt;<br>                    result.sendResult(tracks.map { createTrackItem(it) }.toMutableList())<br>                }<br>            }<br>            parentId.startsWith(&quot;ARTIST_&quot;) -&gt; {<br>                val artistId = parentId.substringAfter(&quot;ARTIST_&quot;)<br>                helper.fetchAlbumsForArtist(artistId) { albums -&gt;<br>                    result.sendResult(albums.map { createAlbumItem(it) }.toMutableList())<br>                }<br>            }<br>            parentId.startsWith(&quot;PLAYLIST_&quot;) -&gt; {<br>                val playlistId = parentId.substringAfter(&quot;PLAYLIST_&quot;)<br>                helper.fetchTracksForPlaylist(playlistId) { tracks -&gt;<br>                    result.sendResult(tracks.map { createTrackItem(it) }.toMutableList())<br>                }<br>            }<br>            else -&gt; result.sendResult(mutableListOf()) // Empty for invalid IDs<br>        }<br>    }<br>}<br><br>private fun getRootCategories(): MutableList&lt;MediaBrowserCompat.MediaItem&gt; {<br>    return mutableListOf(<br>        createBrowsableItem(&quot;ARTISTS&quot;, &quot;Artists&quot;, R.drawable.ic_artists),<br>        createBrowsableItem(&quot;ALBUMS&quot;, &quot;Albums&quot;, R.drawable.ic_albums),<br>        createBrowsableItem(&quot;PLAYLISTS&quot;, &quot;Playlists&quot;, R.drawable.ic_playlists)<br>    )<br>}<br><br>private fun createBrowsableItem(id: String, title: String, iconRes: Int): MediaBrowserCompat.MediaItem {<br>    val uri = Uri.parse(&quot;android.resource://${packageName}/$iconRes&quot;)<br>    val desc = MediaDescriptionCompat.Builder()<br>        .setMediaId(id)<br>        .setTitle(title)<br>        .setIconUri(uri)<br>        .build()<br>    return MediaBrowserCompat.MediaItem(desc, MediaBrowserCompat.MediaItem.FLAG_BROWSABLE)<br>}<br><br>private fun createTrackItem(track: Track): MediaBrowserCompat.MediaItem {<br>    val desc = MediaDescriptionCompat.Builder()<br>        .setMediaId(track.id)<br>        .setTitle(track.title)<br>        .setSubtitle(track.artist)<br>        .setIconUri(Uri.parse(track.artworkUrl))<br>        .build()<br>    return MediaBrowserCompat.MediaItem(desc, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)<br>}</pre><ul><li><strong>What’s Happening</strong>:</li><li>result.detach() lets me fetch data async (API calls can be slow).</li><li>For “root,” I return top-level categories (Artists, Albums, Playlists) as browsable items.</li><li>For “ARTISTS,” I fetch a list of artists (e.g., from a Room DB or API via MusicUseCase).</li><li>For “ALBUM_123,” I get tracks for that album. Same for artists/playlists.</li><li>Each item is a MediaBrowserCompat.MediaItem, either browsable (folders) or playable (tracks).</li><li><strong>Why It Matters</strong>: This builds the UI users see in the car. A shallow hierarchy (2–3 levels) is key — drivers don’t want to dig through menus.</li><li><strong>Pro Tip</strong>: Cache data locally to speed things up. I use a MusicLifecycleHelper (like a ViewModel) to handle fetches safely with coroutines.</li><li><strong>Important Note</strong>: Don’t return too many items (50–100 max per level) or the UI lags. Also, ensure icons load fast — use local resources or cached images.</li></ul><h3>MusicLifecycleHelper: My Data Fetching Sidekick</h3><p>I created a helper to manage data fetching, ensuring no leaks.</p><pre>class MusicLifecycleHelper private constructor(<br>    private val lifecycleOwner: LifecycleOwner,<br>    private val musicUseCase: MusicUseCase<br>) : DefaultLifecycleObserver {<br>    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())<br><br>    companion object {<br>        @Volatile private var instance: MusicLifecycleHelper? = null<br>        fun getInstance(owner: LifecycleOwner, useCase: MusicUseCase): MusicLifecycleHelper {<br>            return instance ?: synchronized(this) {<br>                instance ?: MusicLifecycleHelper(owner, useCase).also { instance = it }<br>            }<br>        }<br>    }<br><br>    fun fetchArtists(callback: (List&lt;Artist&gt;) -&gt; Unit) {<br>        scope.launch {<br>            try {<br>                val artists = musicUseCase.getArtists().getOrNull() ?: emptyList()<br>                withContext(Dispatchers.Main) { callback(artists) }<br>            } catch (e: Exception) {<br>                withContext(Dispatchers.Main) { callback(emptyList()) }<br>            }<br>        }<br>    }<br><br>    // Similar for albums, playlists, tracks<br><br>    override fun onDestroy(owner: LifecycleOwner) {<br>        scope.cancel()<br>        instance = null<br>        lifecycleOwner.lifecycle.removeObserver(this)<br>    }<br>}</pre><p>Why I Love It: Coroutines with lifecycle awareness = no crashes when the service dies. It’s like a trusty roadie setting up the stage.</p><h3>Controlling Playback: MediaSessionCallback</h3><p>Now, let’s talk about actually playing music. The MediaSessionCallback is where user actions — taps on the car screen, voice commands, or notification buttons — turn into play, pause, skip, or seek. It’s tied to the MediaSessionCompat, which broadcasts state (playing/paused) and metadata (song title, artist) to Android Auto and notifications.</p><p>Here’s my implementation:</p><pre>private inner class MediaSessionCallback : MediaSessionCompat.Callback() {<br>    private val queue: MutableList&lt;MediaSessionCompat.QueueItem&gt; = ArrayList()<br>    private var queueIndex = -1<br><br>    override fun onPrepare() {<br>        if (mediaSession?.isActive == false) {<br>            mediaSession?.isActive = true<br>            Log.d(&quot;MusicService&quot;, &quot;Session activated for prep&quot;)<br>        }<br>    }<br><br>    override fun onAddQueueItem(description: MediaDescriptionCompat) {<br>        Log.d(&quot;MusicService&quot;, &quot;Adding to queue: ${description.title}&quot;)<br>        queue.add(MediaSessionCompat.QueueItem(description, description.hashCode().toLong()))<br>        if (queueIndex == -1) queueIndex = 0<br>        mediaSession?.setQueue(queue)<br>    }<br><br>    override fun onRemoveQueueItem(description: MediaDescriptionCompat) {<br>        Log.d(&quot;MusicService&quot;, &quot;Removing from queue: ${description.title}&quot;)<br>        queue.remove(MediaSessionCompat.QueueItem(description, description.hashCode().toLong()))<br>        if (queue.isEmpty()) queueIndex = -1<br>        mediaSession?.setQueue(queue)<br>    }<br><br>    override fun onPlayFromMediaId(mediaId: String?, extras: Bundle?) {<br>        Log.d(&quot;MusicService&quot;, &quot;Playing media ID: $mediaId&quot;)<br>        if (mediaId != null) {<br>            musicUseCase.getTrack(mediaId) { track -&gt;<br>                if (track != null) {<br>                    currentTrack = track<br>                    prepareAndPlay(track)<br>                    updateMetadata(track)<br>                    updatePlaybackState(PlaybackStateCompat.STATE_PLAYING)<br>                } else {<br>                    updatePlaybackState(PlaybackStateCompat.STATE_ERROR)<br>                }<br>            }<br>        }<br>    }<br><br>    override fun onPlay() {<br>        Log.d(&quot;MusicService&quot;, &quot;Play requested&quot;)<br>        if (requestAudioFocus()) {<br>            player?.play()<br>            updatePlaybackState(PlaybackStateCompat.STATE_PLAYING)<br>            playAction = generateAction(PlaybackStateCompat.ACTION_PLAY_PAUSE, R.drawable.ic_pause, &quot;Pause&quot;)<br>            updateNotification()<br>        }<br>    }<br><br>    override fun onPause() {<br>        Log.d(&quot;MusicService&quot;, &quot;Pause requested&quot;)<br>        player?.pause()<br>        updatePlaybackState(PlaybackStateCompat.STATE_PAUSED)<br>        playAction = generateAction(PlaybackStateCompat.ACTION_PLAY_PAUSE, R.drawable.ic_play, &quot;Play&quot;)<br>        updateNotification()<br>    }<br><br>    override fun onSkipToNext() {<br>        Log.d(&quot;MusicService&quot;, &quot;Skip to next&quot;)<br>        val nextTrack = getNextTrack()<br>        if (nextTrack != null) {<br>            prepareAndPlay(nextTrack)<br>            updateMetadata(nextTrack)<br>            updatePlaybackState(PlaybackStateCompat.STATE_PLAYING)<br>        }<br>    }<br><br>    override fun onSkipToPrevious() {<br>        Log.d(&quot;MusicService&quot;, &quot;Skip to previous&quot;)<br>        val prevTrack = getPreviousTrack()<br>        if (prevTrack != null) {<br>            prepareAndPlay(prevTrack)<br>            updateMetadata(prevTrack)<br>            updatePlaybackState(PlaybackStateCompat.STATE_PLAYING)<br>        }<br>    }<br><br>    override fun onSeekTo(pos: Long) {<br>        Log.d(&quot;MusicService&quot;, &quot;Seek to $pos&quot;)<br>        if (currentTrack?.isSeekable == true) {<br>            player?.seekTo(pos)<br>            updatePlaybackState(PlaybackStateCompat.STATE_PLAYING, pos)<br>        }<br>    }<br><br>    override fun onStop() {<br>        Log.d(&quot;MusicService&quot;, &quot;Stop requested&quot;)<br>        player?.stop()<br>        updatePlaybackState(PlaybackStateCompat.STATE_STOPPED)<br>        abandonAudioFocus()<br>        ServiceCompat.stopForeground(this@MusicService, ServiceCompat.STOP_FOREGROUND_REMOVE)<br>        stopSelf()<br>    }<br><br>    private fun prepareAndPlay(track: Track) {<br>        player?.setMediaItem(MediaItem.fromUri(track.streamUrl))<br>        player?.prepare()<br>        player?.play()<br>    }<br><br>    private fun updateMetadata(track: Track) {<br>        val metadata = MediaMetadataCompat.Builder()<br>            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, track.title)<br>            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, track.artist)<br>            .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, track.durationMs)<br>            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, track.artworkUrl)<br>            .build()<br>        mediaSession?.setMetadata(metadata)<br>    }<br><br>    private fun updatePlaybackState(state: Int, position: Long = player?.currentPosition ?: 0) {<br>        val builder = PlaybackStateCompat.Builder()<br>            .setActions(<br>                PlaybackStateCompat.ACTION_PLAY_PAUSE or<br>                        PlaybackStateCompat.ACTION_SKIP_TO_NEXT or<br>                        PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or<br>                        PlaybackStateCompat.ACTION_SEEK_TO<br>            )<br>            .setState(state, position, 1.0f, SystemClock.elapsedRealtime())<br>        if (state == PlaybackStateCompat.STATE_PLAYING) {<br>            builder.setBufferedPosition(track?.durationMs ?: 0)<br>        }<br>        mediaSession?.setPlaybackState(builder.build())<br>        updateNotification()<br>    }<br><br><br>}</pre><ul><li><strong>onPrepare</strong>: Gets the session ready for action. I activate it if it’s not already, so Auto knows we’re live.</li><li><strong>Queue Stuff (onAddQueueItem, onRemoveQueueItem)</strong>: I manage a playlist queue for users who want to line up tracks. Auto shows the queue in its UI, and notifications can reflect “Next: Song Name.”</li><li><strong>onPlayFromMediaId</strong>: The big one — when a user picks a track in Auto (e.g., taps “Bohemian Rhapsody”). I fetch the track, load it into ExoPlayer, and update metadata/state.</li><li><strong>onPlay, onPause</strong>: Toggle playback. I swap the play/pause button in notifications and ensure focus is granted.</li><li><strong>onSkipToNext, onSkipToPrevious</strong>: Navigate tracks in the queue or album. I check the current track’s context to pick the next/previous.</li><li><strong>onSeekTo</strong>: For seekable tracks (not live streams), I jump to the position and update the progress bar.</li><li><strong>onStop</strong>: Full stop — cleans up, kills the service, removes notifications.</li><li><strong>Why It’s Cool</strong>: This ties everything together. Auto’s taps, voice commands, and notification clicks all hit these methods. I update the session’s state/metadata, which syncs to the car and notification bar.</li><li><strong>Notification Link</strong>: Every action updates PlaybackStateCompat and MediaMetadataCompat, triggering a notification refresh. For example, onPlay swaps to a pause button, onSeekTo moves the progress bar.</li><li><strong>Important Note</strong>: It is essential to verify and properly manage audio focus within the onPlay() method. Failing to do so can result in undesirable behavior, such as media playback continuing during an active phone call.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wffUWTLl7-9Ua4ARxJbquQ.png" /><figcaption>Display media artwork</figcaption></figure><h3>Notifications: Keeping Users in Control</h3><p>Notifications are like the dashboard’s sidekick. They show up on the phone’s lock screen, in Auto’s UI, and even on wearables. They’re tied to the media session, so every state change (play, pause, new track) updates them automatically.</p><pre>private fun createNotificationChannel() {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>        val channel = NotificationChannel(CHANNEL_ID, &quot;Music Playback&quot;, NotificationManager.IMPORTANCE_DEFAULT).apply {<br>            setSound(null, null) // Silent for media<br>            enableVibration(false)<br>            lockscreenVisibility = Notification.VISIBILITY_PUBLIC<br>        }<br>        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)<br>    }<br>}<br><br>private fun updateNotification() {<br>    val isPlaying = mediaSession?.playbackState?.state == PlaybackStateCompat.STATE_PLAYING<br>    val builder = NotificationCompat.Builder(this, CHANNEL_ID)<br>        .setStyle(androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(mediaSession?.sessionToken))<br>        .setSmallIcon(R.drawable.ic_music)<br>        .setContentTitle(currentTrack?.title ?: &quot;No Track&quot;)<br>        .setContentText(currentTrack?.artist)<br>        .setSubText(currentTrack?.album)<br>        .setLargeIcon(loadArtwork(currentTrack?.artworkUrl))<br>        .addAction(prevAction ?: generateAction(PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS, R.drawable.ic_prev, &quot;Previous&quot;))<br>        .addAction(if (isPlaying) pauseAction ?: generateAction(PlaybackStateCompat.ACTION_PLAY_PAUSE, R.drawable.ic_pause, &quot;Pause&quot;)<br>                  else playAction ?: generateAction(PlaybackStateCompat.ACTION_PLAY_PAUSE, R.drawable.ic_play, &quot;Play&quot;))<br>        .addAction(nextAction ?: generateAction(PlaybackStateCompat.ACTION_SKIP_TO_NEXT, R.drawable.ic_next, &quot;Next&quot;))<br>        .setOngoing(isPlaying)<br>        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)<br>        .setContentIntent(createPendingIntent())<br><br>    val notification = builder.build()<br>    if (isPlaying &amp;&amp; !isForeground) {<br>        startForeground(NOTIFICATION_ID, notification)<br>        isForeground = true<br>    } else {<br>        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).notify(NOTIFICATION_ID, notification)<br>    }<br>}<br><br>private fun generateAction(action: Long, icon: Int, title: String): NotificationCompat.Action {<br>    val intent = MediaButtonReceiver.buildMediaButtonPendingIntent(this, action)<br>    return NotificationCompat.Action.Builder(icon, title, intent).build()<br>}<br><br>private fun createPendingIntent(): PendingIntent {<br>    val intent = Intent(this, MainActivity::class.java).apply {<br>        flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP<br>        putExtra(&quot;fromNotification&quot;, true)<br>    }<br>    val flags = if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) {<br>        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE<br>    } else {<br>        PendingIntent.FLAG_UPDATE_CURRENT<br>    }<br>    return PendingIntent.getActivity(this, 0, intent, flags)<br>}<br><br>private fun loadArtwork(url: String?): Bitmap? {<br>    return try {<br>        Glide.with(this).asBitmap().load(url).override(300, 300).submit().get()<br>    } catch (e: Exception) {<br>        Log.e(&quot;MusicService&quot;, &quot;Failed to load artwork: $e&quot;)<br>        null<br>    }<br>}</pre><ul><li><strong>What’s Happening</strong>:</li><li><strong>Channel</strong>: Silent, public for lock screen visibility.</li><li><strong>Builder</strong>: Uses MediaStyle to auto-pull session metadata. I add prev/play-pause/next actions, tied to MediaButtonReceiver for callback routing.</li><li><strong>Foreground</strong>: During play, it’s a foreground service to stay alive.</li><li><strong>Pending Intent</strong>: Tapping the notification opens the app.</li><li><strong>Artwork</strong>: Glide loads album art async for the big icon.</li><li><strong>Why It Matters</strong>: Notifications are the user’s control panel outside Auto’s UI. They sync with the session, so a pause in Auto updates the notification instantly.</li><li><strong>Pro Tip</strong>: Keep actions simple (3–4 max) for compact views. Use high-res art but optimize for size.</li><li><strong>Important Note</strong>: Without startForeground, the system might kill your service during playback.</li></ul><h3>Cleaning Up: Lifecycle Management</h3><p>I handle service lifecycle to avoid leaks or zombie processes.</p><pre>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>    MediaButtonReceiver.handleIntent(mediaSession, intent)<br>    return START_NOT_STICKY<br>}<br><br>override fun onDestroy() {<br>    mediaSession?.release()<br>    player?.release()<br>    abandonAudioFocus()<br>    (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).cancel(NOTIFICATION_ID)<br>    lifecycleRegistry.currentState = Lifecycle.State.DESTROYED<br>    super.onDestroy()<br>}</pre><ul><li><strong>Start</strong>: Handle media button intents (e.g., headset play/pause).</li><li><strong>Destroy</strong>: Release resources, cancel notifications, stop being foreground.</li></ul><h3>Taking It Further: Testing, Voice, and More</h3><ul><li><strong>Testing</strong>: I used the DHU emulator (adb forward tcp:5277). Logcat is your friend for debugging connection issues.</li><li><strong>Voice Commands</strong>: Support ACTION_PLAY_FROM_SEARCH for “Play [artist]” queries. Test with Assistant in the emulator.</li><li><strong>Offline Mode</strong>: Cache tracks/metadata in Room DB for spotty connections.</li><li><strong>Analytics</strong>: I log plays/skips to Firebase to track what drivers love.</li><li><strong>Performance</strong>: Paginate onLoadChildren results (50 items max). Compress images to avoid lag.</li></ul><h3>My Lessons Learned</h3><ul><li><strong>Don’t Skip Audio Focus</strong>: I ignored it early on, and users got annoyed when music overlapped calls.</li><li><strong>Keep Hierarchies Shallow</strong>: Deep menus frustrate drivers. Stick to 2–3 levels.</li><li><strong>Test on Real Devices</strong>: Emulators are great, but cars reveal quirks (e.g., screen sizes).</li><li><strong>Notifications Are Key</strong>: They’re not just UI — they keep your service alive and users in control.</li></ul><h3>Wrapping Up: Why This Rocks</h3><p>Building Android Auto support was a ton of work, but seeing my app light up a car’s dashboard? Priceless. Users can browse their favorite artists, queue playlists, and skip tracks without taking their eyes off the road. Plus, it’s a competitive edge — nobody wants to be the app left out of the car.</p><p>I hope this guide saves you some headaches. If you’re building this, drop me a comment with your wins or struggles! For the full code, check my GitHub: <a href="https://github.com/Cevik10/AndroidAutoSampleProject">https://github.com/Cevik10/AndroidAutoSampleProject</a>. Now, go make your app the soundtrack to someone’s drive!</p><p>For further details and the official guidelines, I recommend reviewing the Android documentation:</p><ul><li><a href="https://developer.android.com/training/cars/media">Android Developers — Build media apps for cars</a></li><li><a href="https://developer.android.com/reference/androidx/media/MediaBrowserServiceCompat">AndroidX Media — MediaBrowserServiceCompat Reference</a></li><li><a href="https://developer.android.com/training/cars">Android Auto Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c239d6a2c494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3D Modeling with SceneView in Android: Animations, Nodes, Scenes, and GLB Optimization]]></title>
            <link>https://medium.com/@hakanxcevik7/3d-modeling-with-sceneview-in-android-animations-nodes-scenes-and-glb-optimization-68cf5a1048c8?source=rss-5902460faa66------2</link>
            <guid isPermaLink="false">https://medium.com/p/68cf5a1048c8</guid>
            <category><![CDATA[glb]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Hakan Cevik]]></dc:creator>
            <pubDate>Wed, 14 May 2025 23:51:22 GMT</pubDate>
            <atom:updated>2025-05-17T02:00:21.232Z</atom:updated>
            <content:encoded><![CDATA[<p>3D modeling in Android applications is a powerful tool to enhance user experiences. From gaming and education to e-commerce and architectural visualization, 3D models have become an integral part of modern mobile apps. In this article, we will explore how to use the <a href="https://github.com/SceneView/sceneview-android">SceneView library</a> for 3D modeling in Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpcpvKaNerPSz_gP6cnl8A.png" /></figure><p>We’ll cover animations, nodes, scenes, and the optimization of GLB files, along with integration into Jetpack Compose. We’ll also discuss how unoptimized GLB files can inflate app size and how to mitigate related performance issues.</p><h3>What is SceneView?</h3><p>SceneView is an Android library built on Google’s <a href="https://github.com/google/filament">Filament rendering engine</a> and integrated with <a href="https://developers.google.com/ar">ARCore</a>. It empowers developers to add 3D and augmented reality (AR) capabilities to their apps. SceneView consists of two main components:</p><ul><li><strong>SceneView</strong>: Used for rendering 3D models.</li><li><strong>ARSceneView</strong>: Extends 3D rendering with AR features.</li></ul><p>This article focuses on 3D modeling with SceneView. The library supports .glb and .gltf file formats and integrates seamlessly with Jetpack Compose, making it ideal for modern Android development. SceneView delivers high-quality visuals while offering a flexible API for developers.</p><h3>Adding SceneView to Your Project</h3><p>To start using SceneView, add it to your project by including the dependency in your Gradle file:</p><pre>dependencies {<br>    implementation &#39;io.github.sceneview:sceneview-android:1.0.0&#39;<br>}</pre><p>Next, place your 3D models (e.g., ship.glb) in the assets folder of your app, such as assets/models/ship.glb. If you plan to use AR features, ensure your app’s manifest includes the necessary permissions:</p><pre>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;<br>&lt;uses-feature android:name=&quot;android.hardware.camera.ar&quot; /&gt;<br>&lt;meta-data android:name=&quot;com.google.ar.core&quot; android:value=&quot;required&quot; /&gt;</pre><h3>Loading and Rendering 3D Models</h3><p>Loading 3D models with SceneView is straightforward. Models are added to the scene using ModelNode. Here’s an example of how to load a model:</p><pre>val modelLoader = rememberModelLoader(engine)<br>val modelNode = rememberNode {<br>    ModelNode(<br>        modelInstance = modelLoader.createModelInstance(&quot;models/ship.glb&quot;),<br>        scaleToUnits = 1.0f<br>    )<br>}</pre><p>This code loads the ship.glb model from the assets/models/ directory and adds it to the scene as a ModelNode. The scaleToUnits parameter adjusts the model’s size to fit the scene appropriately.</p><h3>Optimizing GLB Files</h3><p>GLB files are a popular format for 3D models in Android apps, but without optimization, they can significantly increase app size and cause performance issues. Large GLB files may lead to memory errors (e.g., OutOfMemoryError) and slow rendering, as noted in <a href="https://github.com/SceneView/sceneform-android/discussions/153">GitHub discussions</a>. Optimization is crucial to maintain app efficiency.</p><p><strong>Techniques for Optimizing GLB Files:</strong></p><ul><li><strong>Texture Compression:</strong> Reduce texture file sizes using efficient formats like KTX2 (though SceneView may have rendering issues with KTX2, see <a href="https://github.com/SceneView/sceneview-android/issues/86">GitHub Issue #86</a>).</li><li><strong>Polygon Reduction:</strong> Decrease the number of polygons in the model to lower file size and rendering time.</li><li><strong>Online Validation Tools:</strong> Use Google’s <a href="https://developers.google.com/ar/develop/scene-viewer">Scene Viewer previewer</a> to validate and optimize GLB or GLTF files and their textures.</li><li><strong>File Size Management:</strong> Keep GLB file sizes as small as possible to avoid issues, especially on low-memory devices.</li><li><strong>Testing and Validation:</strong> Test models across different devices and use profiling tools to identify performance bottlenecks.</li></ul><h3>Managing Scenes and Nodes</h3><p>In SceneView, a scene is a container for 3D models, cameras, lights, and other elements. Scenes are populated with nodes, organized in a hierarchical structure. Key node types include:</p><ul><li><strong>CameraNode</strong>: Defines the camera’s position and orientation.</li><li><strong>ModelNode</strong>: Represents a 3D model.</li><li><strong>CenterNode</strong>: Groups other nodes and typically serves as the scene’s center.</li></ul><p>Here’s an example of creating a scene with nodes:</p><pre>val cameraNode = rememberCameraNode(engine).apply { position = Position(z = 4.0f) }<br>val centerNode = rememberNode(engine).apply { addChildNode(cameraNode) }<br>val modelNode = rememberNode {<br>    ModelNode(<br>        modelInstance = modelLoader.createModelInstance(assetFileLocation),<br>        scaleToUnits = scaleToUnits<br>    )<br>}<br><br>Scene(<br>    modifier = Modifier.fillMaxSize(),<br>    engine = engine,<br>    modelLoader = modelLoader,<br>    cameraNode = cameraNode,<br>    childNodes = listOf(centerNode, modelNode)<br>)</pre><p>In this example:</p><ul><li>cameraNode positions the camera 4 units away for a clear view of the model.</li><li>centerNode groups the camera and acts as the scene’s center.</li><li>modelNode loads and adds the 3D model.</li><li>Scene combines these components for rendering.</li></ul><p>The hierarchical structure of nodes simplifies the management of complex scenes, enabling developers to handle multiple model parts or adjust camera perspectives.</p><h3>Animations</h3><p>SceneView supports animations for models and cameras, which can be triggered by user interactions or timed events. Let’s explore two common animation types: rotation and circular motion.</p><h3>Rotation Animation</h3><p>To rotate the camera around a model, use animateRotation. This example rotates the camera 360 degrees around the y-axis:</p><pre>val rotationAnimation = rememberInfiniteTransition(label = &quot;RotationTransition&quot;)<br>val cameraRotation by if (isRotating) {<br>    rotationAnimation.animateRotation(<br>        initialValue = Rotation(y = 0.0f),<br>        targetValue = Rotation(y = 360.0f),<br>        animationSpec = infiniteRepeatable(<br>            animation = tween(durationMillis = rotationDuration.toInt(DurationUnit.MILLISECONDS))<br>        )<br>    )<br>} else {<br>    remember { mutableStateOf(Rotation(y = 0.0f)) }<br>}<br><br>centerNode.rotation = cameraRotation</pre><p>When isRotating is true, the camera rotates around the model in a 20-second loop, repeating indefinitely with infiniteRepeatable. Users can toggle this animation via a button.</p><h3>Circular Motion Animation</h3><p>To move a model along a circular path, use animateFloatAsState:</p><pre>val engageProgress by animateFloatAsState(<br>    targetValue = if (isEngaging) 1f else 0f,<br>    animationSpec = tween(durationMillis = ModelViewerConfig.EngageAnimationDuration),<br>    finishedListener = { if (isEngaging) onEngageToggle() }<br>)<br><br>val radius = ModelViewerConfig.CircularPathRadius<br>val angle = engageProgress * 2 * Math.PI.toFloat()<br>val position = if (isEngaging) {<br>    Position(x = radius * cos(angle), y = 0f, z = radius * sin(angle))<br>} else {<br>    Position(0f, 0f, 0f)<br>}<br><br>modelNode.position = position</pre><p>When isEngaging is true, the model moves along a circular path with a 2-unit radius over 5 seconds. The animation stops when complete, calling onEngageToggle. This can simulate dynamic movements, like a spaceship orbiting.</p><h3>Integration with Jetpack Compose</h3><p>SceneView integrates seamlessly with Jetpack Compose. The Scene composable renders 3D scenes and can be combined with other UI elements. Here’s an example of a 3D model viewer:</p><pre>@Composable<br>fun ModelViewer(<br>    modifier: Modifier = Modifier,<br>    assetFileLocation: String,<br>    isRotating: Boolean,<br>    isEngaging: Boolean,<br>    onRotationToggle: () -&gt; Unit,<br>    onEngageToggle: () -&gt; Unit,<br>    rotationDuration: Duration = ModelViewerConfig.RotationDuration,<br>    cameraPosition: Position = ModelViewerConfig.CameraPosition,<br>    scaleToUnits: Float = ModelViewerConfig.ScaleToUnits<br>) {<br>    val engine = rememberEngine()<br>    DisposableEffect(Unit) {<br>        onDispose {<br>            engine.destroy()<br>        }<br>    }<br>    val modelLoader = rememberModelLoader(engine)<br>    val cameraNode = rememberCameraNode(engine).apply { position = cameraPosition }<br>    val centerNode = rememberNode(engine).apply { addChildNode(cameraNode) }<br>    val modelNode = rememberNode {<br>        ModelNode(<br>            modelInstance = modelLoader.createModelInstance(assetFileLocation),<br>            scaleToUnits = scaleToUnits<br>        )<br>    }<br><br>    val rotationAnimation = rememberInfiniteTransition(label = &quot;RotationTransition&quot;)<br>    val cameraRotation by if (isRotating) {<br>        rotationAnimation.animateRotation(<br>            initialValue = Rotation(y = 0.0f),<br>            targetValue = Rotation(y = 360.0f),<br>            animationSpec = infiniteRepeatable(<br>                animation = tween(durationMillis = rotationDuration.toInt(DurationUnit.MILLISECONDS))<br>            )<br>        )<br>    } else {<br>        remember { mutableStateOf(Rotation(y = 0.0f)) }<br>    }<br><br>    val engageProgress by animateFloatAsState(<br>        targetValue = if (isEngaging) 1f else 0f,<br>        animationSpec = tween(durationMillis = ModelViewerConfig.EngageAnimationDuration),<br>        finishedListener = { if (isEngaging) onEngageToggle() }<br>    )<br><br>    val radius = ModelViewerConfig.CircularPathRadius<br>    val angle = engageProgress * 2 * Math.PI.toFloat()<br>    val position = if (isEngaging) {<br>        Position(x = radius * cos(angle), y = 0f, z = radius * sin(angle))<br>    } else {<br>        Position(0f, 0f, 0f)<br>    }<br><br>    Scene(<br>        modifier = modifier.background(Color.Transparent),<br>        engine = engine,<br>        modelLoader = modelLoader,<br>        cameraNode = cameraNode,<br>        isOpaque = false,<br>        childNodes = listOf(centerNode, modelNode),<br>        onFrame = {<br>            centerNode.rotation = cameraRotation<br>            modelNode.position = position<br>            cameraNode.lookAt(modelNode)<br>        }<br>    )<br>}</pre><p>This function:</p><ul><li>Loads a 3D model from assetFileLocation.</li><li>Rotates the camera if isRotating is true.</li><li>Moves the model in a circle if isEngaging is true.</li><li>Uses DisposableEffect to clean up the engine, preventing memory leaks.</li><li>Updates node positions and rotations per frame with onFrame.</li></ul><p>Compose integration allows you to embed 3D scenes into modern Android UIs, enhancing them with toolbars or interactive buttons.</p><h3>Best Practices</h3><p>When using SceneView, consider these best practices:</p><ul><li><strong>Resource Management:</strong> Properly dispose of the engine and resources (e.g., via DisposableEffect) to avoid memory leaks.</li><li><strong>Performance Optimization:</strong> Minimize resource usage for animations and rendering. Optimize complex animations.</li><li><strong>User Experience:</strong> Adjust animation durations and movements to be user-friendly avoid overly long animations.</li><li><strong>Permissions:</strong> Manage camera and ARCore permissions correctly if using AR features.</li><li><strong>GLB Optimization:</strong> Compress textures, reduce model sizes, and validate with online tools to keep app size and performance in check.</li><li><strong>Device Testing:</strong> Test across various devices to ensure compatibility and performance.</li></ul><h3>Conclusion</h3><p>SceneView is a game changer for Android developers seeking to incorporate 3D modeling and animations into their applications. Its foundation on the Filament engine delivers high-quality rendering, while its integration with ARCore and Jetpack Compose positions it as a forward-thinking solution for modern app development. In this extensive guide, we’ve covered the essentials setting up SceneView, loading and rendering models, optimizing GLB files, managing scenes and nodes, creating animations, and building interactive UIs with Compose.</p><p>By mastering these concepts, you can craft immersive experiences that captivate users, whether you’re building a game, a virtual showroom, or an educational tool. The key to success lies in balancing visual richness with performance, a challenge SceneView empowers you to meet head on. Start experimenting with SceneView today, and unlock the potential of 3D in your Android projects your users will thank you for the next-level experiences you create.</p><h3>Additional Resources</h3><ul><li>Visit the <a href="https://github.com/SceneView/sceneview-android">SceneView GitHub page</a> for updates and sample projects.</li><li>The <a href="https://developers.google.com/ar/develop/scene-viewer">Scene Viewer documentation</a> offers insights into GLB optimization.</li><li>Explore the <a href="https://github.com/google/filament">Filament site</a> for technical details on the rendering engine.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68cf5a1048c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securely Storing API Keys in Android with Kotlin]]></title>
            <link>https://medium.com/@hakanxcevik7/android-kotlinde-api-anahtarlar%C4%B1n%C4%B1-g%C3%BCvenli-bir-%C5%9Fekilde-saklamak-3c333506b269?source=rss-5902460faa66------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c333506b269</guid>
            <category><![CDATA[secure-api-key]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Hakan Cevik]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 14:11:06 GMT</pubDate>
            <atom:updated>2025-03-16T11:18:27.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnrMajhGfv8OlY_X-XN2HA.jpeg" /></figure><p>When developing Android applications, securely storing API keys is of great importance. In this article, I will share how you can securely store API keys in Android using Kotlin. First, we will start with how you should <em>not</em> store API keys, and then we will explain the secure methods you can use. I will cover a few approaches you can adopt: Gradle BuildConfig, EncryptedSharedPreferences, and using a secure server.</p><h3>How Not to Store API Keys?</h3><h3>Storing Directly in Code</h3><p>Storing API keys directly in the code is one of the most common mistakes. This method exposes the keys in places where malicious actors can easily find them.</p><p>Incorrect Method:</p><pre>apiKey = &quot;YOUR_API_KEY_HERE&quot;</pre><p>This approach stores your key within your application’s source code, making it easily accessible when the APK file is extracted.</p><h3>Storing Using ProGuard</h3><p>ProGuard is used for code obfuscation, but it is not a reliable method for storing API keys. Malicious actors can reverse-engineer the obfuscated code and retrieve your key.</p><p>Incorrect Method:</p><pre>// build.gradle<br>buildTypes {<br>    release {<br>        minifyEnabled true<br>        proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>    }<br>}</pre><h3>Hard-Coded Strings</h3><p>Using hard-coded strings within the application can make your API keys easily discoverable.</p><p>Incorrect Method:</p><pre>fun getApiKey(): String {<br>    return &quot;YOUR_API_KEY_HERE&quot;<br>}</pre><p>Storing API keys using these methods compromises your application’s security and may lead to unauthorized access by malicious actors.</p><h3>Storing API Keys with Gradle BuildConfig</h3><p>Storing API keys using BuildConfig is a safer approach compared to storing them directly in the code. Here’s how you can do it step by step:</p><h4>Step 1: Add the API Key to the Gradle Properties File</h4><p>First, add your API key to the gradle.properties file:</p><pre>API_KEY=&quot;YOUR_API_KEY_HERE&quot;</pre><h4>Step 2: Add BuildConfigField to the build.gradle File</h4><p>Next, add the following lines to your build.gradle (Module: app) file:</p><pre>groovy</pre><pre>android {<br>    ...<br>    defaultConfig {<br>        ...<br>        buildConfigField &quot;String&quot;, &quot;API_KEY&quot;, &quot;\&quot;${API_KEY}\&quot;&quot;<br>    }<br>}</pre><h4>Step 3: Access the API Key Using BuildConfig</h4><p>Finally, you can use the API key as follows:</p><pre>val apiKey = BuildConfig.API_KEY<br>Log.d(&quot;API_KEY&quot;, apiKey)</pre><p>This method is safer than storing the key directly in the code, but it can still be extracted from the APK file. Therefore, you may want to consider a more secure approach.</p><h3>Storing API Keys with EncryptedSharedPreferences</h3><p>EncryptedSharedPreferences allows you to securely store sensitive data by encrypting it. Here’s how you can do it:</p><h3>Step 1: Create a MasterKey</h3><p>First, create the MasterKey, which will be used for encryption and decryption:</p><pre>val masterKeyAlias = MasterKey.Builder(this)<br>    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)<br>    .build()</pre><h3>Step 2: Create EncryptedSharedPreferences</h3><p>Next, create an instance of EncryptedSharedPreferences:</p><pre>val sharedPreferences = EncryptedSharedPreferences.create(<br>    this,<br>    &quot;secret_shared_prefs&quot;,<br>    masterKeyAlias,<br>    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,<br>    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM<br>)</pre><h3>Step 3: Store Data in EncryptedSharedPreferences</h3><p>You can store your API key in EncryptedSharedPreferences as follows:</p><pre>sharedPreferences.edit().putString(&quot;API_KEY&quot;, &quot;YOUR_API_KEY_HERE&quot;).apply()</pre><h3>Step 4: Retrieve Data from EncryptedSharedPreferences</h3><p>You can read your API key as follows:</p><pre>val apiKey = sharedPreferences.getString(&quot;API_KEY&quot;, null)<br>Log.d(&quot;API_KEY&quot;, apiKey)</pre><p>This method securely stores your keys on the device, making it harder for malicious actors to access them.</p><h3>Storing API Keys on a Secure Server</h3><p>One of the most secure methods is to store API keys on a secure server and use them on the client side. This way, users cannot directly see the API keys.</p><h3>Server-Side (Node.js Example)</h3><p>You can store your API key using a simple Node.js server:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = 3000;</pre><pre>app.get(&#39;/getApiKey&#39;, (req, res) =&gt; {<br>    res.json({ apiKey: process.env.API_KEY });<br>});</pre><pre>app.listen(port, () =&gt; {<br>    console.log(`Server running at <a href="http://localhost:${port}`);">http://localhost:${port}`);</a><br>});</pre><h3>Client-Side (Using Kotlin and Retrofit)</h3><p>You can use Retrofit to retrieve your API key from the server:</p><h4>ApiService Interface</h4><pre>interface ApiService {<br>    @GET(&quot;/getApiKey&quot;)<br>    suspend fun getApiKey(): ApiKeyResponse<br>}</pre><pre>data class ApiKeyResponse(val apiKey: String)</pre><h4>Fetching the API Key with Retrofit</h4><pre>val retrofit = Retrofit.Builder()<br>    .baseUrl(&quot;http://yourserver.com&quot;)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><pre>val apiService = retrofit.create(ApiService::class.java)</pre><pre>suspend fun fetchApiKey(): String {<br>    return withContext(Dispatchers.IO) {<br>        val response = apiService.getApiKey()<br>        response.apiKey<br>    }<br>}</pre><h4>Here’s how you can get the API key in your MainActivity:</h4><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        lifecycleScope.launch {<br>            val apiKey = fetchApiKey()<br>            Log.d(&quot;API_KEY&quot;, apiKey)<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>There are several methods to securely store API keys in Android applications. Avoid storing API keys directly in the code, using Proguard for storage, or using hard-coded strings. Instead, consider using methods like Gradle BuildConfig, EncryptedSharedPreferences, or storing the keys on a secure server. Each method offers different levels of security, and you can choose the one that best fits your project’s requirements and security priorities.</p><p>By securely storing your API keys, you can enhance the security of your application and make it more difficult for malicious users to access these keys.</p><p>I hope this article helps you store API keys securely in your Android applications. If you have any questions or feedback, feel free to share them in the comments. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c333506b269" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Android App Security and Optimization with R8 and ProGuard]]></title>
            <link>https://medium.com/@hakanxcevik7/r8-ve-proguard-ile-android-uygulama-optimizasyonu-1745a6ea8747?source=rss-5902460faa66------2</link>
            <guid isPermaLink="false">https://medium.com/p/1745a6ea8747</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[google-play-services]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Hakan Cevik]]></dc:creator>
            <pubDate>Thu, 30 May 2024 13:15:00 GMT</pubDate>
            <atom:updated>2025-03-16T10:57:40.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Android application development process involves using tools like R8 and ProGuard to reduce the size of your application and protect your code. In this article, you will learn how to optimize your application using R8 and ProGuard, how to perform code obfuscation, and discover best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nr8DQO7eoV4thYKn-Zv6eA.jpeg" /></figure><h3>What Are R8 and ProGuard?</h3><blockquote><strong>ProGuard </strong>is a tool used to shrink the size of your Android application and enhance its security by obfuscating the code. <strong>R8</strong>, on the other hand, is a more advanced tool that replaces ProGuard, offering improved optimizations. R8 includes all the features of ProGuard while additionally providing better performance and smaller APK sizes.</blockquote><h3>Using R8 ve ProGuard</h3><blockquote><strong>Gradle Configuration</strong></blockquote><blockquote>Using R8 and ProGuard in Android projects is quite straightforward. You can enable these tools by adding the following lines to your <em>build.gradle</em> file:</blockquote><pre>android {<br>    ...<br>    buildTypes {<br>        release {<br>            minifyEnabled true<br>            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>        }<br>    }<br>}</pre><p>This configuration enables R8 and ProGuard for the releasebuild type and applies the rules specified in the proguard-rules.pro file.</p><blockquote><strong>ProGuard Rules</strong></blockquote><blockquote>ProGuard rules are used to protect specific code segments from obfuscation and optimization. Below are some commonly used ProGuard rules:</blockquote><ul><li><strong>Protecting Specific Classes:</strong></li></ul><pre>-keep class com.example.MyClass { *; }</pre><ul><li><strong>Protecting All Public Methods:</strong></li></ul><pre>-keepclassmembers class * {<br>    public *;<br>}</pre><ul><li><strong>Protecting Android Entry Points:</strong></li></ul><pre>-keepclassmembers class * extends android.app.Activity {<br>    public void *(android.view.View);</pre><h4><strong>Example ProGuard Rules File</strong></h4><p>Your ProGuard rules file, proguard-rules.pro, might look like this:</p><pre># Keep Application class<br>-keep class com.example.MyApplication { *; }</pre><pre># Keep all Activities<br>-keep class * extends android.app.Activity { *; }</pre><pre># Keep all Fragments<br>-keep class * extends androidx.fragment.app.Fragment { *; }</pre><pre># Keep all ViewModels<br>-keep class * extends androidx.lifecycle.ViewModel { *; }</pre><pre># Keep all data classes<br>-keepclassmembers class * {<br>    @com.google.gson.annotations.SerializedName &lt;fields&gt;;<br>}</pre><pre># Keep Retrofit interfaces<br>-keep class * {<br>    @retrofit2.http.* &lt;methods&gt;;<br>}</pre><pre># Prevent obfuscation of Glide generated API<br>-keep class com.bumptech.glide.** { *; }</pre><h3><strong>Best Practices for R8 and ProGuard</strong></h3><ol><li><strong>Keep Rules Minimal:</strong> Avoid adding unnecessary rules. Keep your rules specific and tailored to your needs.</li><li><strong>Test Thoroughly:</strong> After enabling R8 and ProGuard, test your application thoroughly. Optimization and obfuscation processes may introduce some errors.</li><li><strong>Review Logs:</strong> Carefully examine the errors and warnings generated during the build process. These logs can provide clues about which classes or methods need to be preserved.</li><li><strong>Add Rules for External Libraries:</strong> Include the necessary ProGuard rules for third-party libraries you use. These rules are typically specified in the library documentation.</li></ol><h3>Conclusion</h3><p>R8 and ProGuard are powerful tools for reducing the size of your Android application and enhancing its security. In this article, you learned how to use these tools and explored best practices. By enabling R8 and ProGuard in your project, you can create smaller and more secure APKs. Don’t forget to leverage these tools effectively to improve your application’s performance and protect your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1745a6ea8747" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>