<?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 Anand Jeyapal on Medium]]></title>
        <description><![CDATA[Stories by Anand Jeyapal on Medium]]></description>
        <link>https://medium.com/@janand1991?source=rss-b6e535d55063------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b0XyVNUtlAIT1Ma4worXgA.jpeg</url>
            <title>Stories by Anand Jeyapal on Medium</title>
            <link>https://medium.com/@janand1991?source=rss-b6e535d55063------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:23:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@janand1991/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[Background Audio Playback in Android using MediaSessionService (Jetpack Compose)]]></title>
            <link>https://medium.com/@janand1991/background-audio-playback-in-android-using-mediasessionservice-jetpack-compose-88214b02266d?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/88214b02266d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[media3]]></category>
            <category><![CDATA[jetpack-media3]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 12:22:40 GMT</pubDate>
            <atom:updated>2025-12-16T12:24:46.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwN15ji_QdPVP3c8ZOu-cg.avif" /></figure><blockquote><strong>Goal</strong>: Build a simple Jetpack Compose screen that plays audio using ExoPlayer and continues playback in the background with a proper media notification using MediaSessionService.</blockquote><p><strong>Why MediaSessionService?</strong></p><p>If you want your audio to:</p><ol><li>Continue when the app is in the background</li><li>Show media controls in the notification shade</li><li>Support lock-screen and headset controls</li></ol><p>…then <strong>MediaSessionService is mandatory</strong>.</p><p>A normal Service or keeping the player in the UI will break as soon as the app is backgrounded.</p><blockquote>Think of MediaSessionService as the official bridge between your player and the Android system.</blockquote><p><strong>What We’ll Build?</strong></p><ul><li>A <strong>Compose screen</strong> with artwork, title, and play/pause controls</li><li>A <strong>MediaController</strong> that talks to a MediaSessionService</li><li>Automatic media notification and lock-screen controls</li><li>Loading indicator until playback is ready</li></ul><p><strong>Dependencies</strong></p><pre>implementation(&quot;androidx.media3:media3-exoplayer:1.3.1&quot;)<br>implementation(&quot;androidx.media3:media3-session:1.3.1&quot;)<br>implementation(&quot;androidx.media3:media3-ui:1.3.1&quot;)<br>implementation(&quot;androidx.compose.material:material-icons-extended:1.5.0&quot;)</pre><p><strong>Step 1: Create the MediaSessionService</strong></p><pre>class AudioPlayerService : MediaSessionService() {<br><br>    lateinit var player: ExoPlayer<br>        private set<br>    private lateinit var mediaSession: MediaSession<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        player = ExoPlayer.Builder(this).build()<br>        mediaSession = MediaSession.Builder(this, player)<br>            .setId(&quot;audio_session&quot;)<br>            .build()<br>    }<br><br>    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession {<br>        return mediaSession<br>    }<br><br>    override fun onDestroy() {<br>        mediaSession.release()<br>        player.release()<br>        super.onDestroy()<br>    }<br>}</pre><p>This service needs to be declared in the AndroidManifest.xml file as below</p><pre>&lt;service<br>    android:name=&quot;.AudioPlayerService&quot;<br>    android:exported=&quot;false&quot;<br>    android:foregroundServiceType=&quot;mediaPlayback&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;androidx.media3.session.MediaSessionService&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><p>Make sure you have the following 3 permissions</p><pre>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt; </pre><p>Internet permission is required to fetch the media source from server.</p><p><strong>Step 2: Compose Audio Player UI</strong></p><p>I added a simple Column component with album artwork, title and artist details. This holds a section which dynamically shows loading/play/pause icon depending on the playback state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82Ct7vZEskWLUXPm10AH-g.jpeg" /></figure><pre>@Composable<br>fun AudioPlayerScreen() {<br>    val context = LocalContext.current<br><br>    var isPlaying by remember { mutableStateOf(false) }<br>    var currentPlaybackState by remember { mutableIntStateOf(Player.STATE_BUFFERING) }<br>    <br>    Column(<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br><br>        // Artwork<br>        Image(<br>            painter = painterResource(id = R.drawable.album_art),<br>            contentDescription = &quot;Album artwork&quot;,<br>            modifier = Modifier<br>                .size(220.dp)<br>                .clip(RoundedCornerShape(16.dp)),<br>            contentScale = ContentScale.Crop<br>        )<br><br>        // Title<br>        Text(text = &quot;Heroes&quot;)<br><br>        // Artist<br>        Text(text = &quot;David Bowie&quot;,)<br><br>        // Dynamic Button<br>        PlayerButton(playbackState = currentPlaybackState, isPlaying = isPlaying)<br>    }<br>}<br><br>@Composable<br>fun PlayerButton(playbackState: Int, isPlaying: Boolean) {<br>    Box(contentAlignment = Alignment.Center) {<br>        if (playbackState == Player.STATE_BUFFERING) {<br>            CircularProgressIndicator()<br>        } else {<br>            IconButton(<br>                modifier = Modifier.size(72.dp), onClick = {<br>                    if (isPlaying) {<br>                        // pause the player<br>                    } else {<br>                        // play the player<br>                    }<br>                }) {<br>                Icon(<br>                    imageVector = if (isPlaying) Icons.Filled.Pause<br>                    else Icons.Filled.PlayArrow,<br>                    contentDescription = &quot;Play Pause&quot;,<br>                    modifier = Modifier.fillMaxSize()<br>                )<br>            }<br>        }<br>    }<br>}</pre><p><strong>Step 3: Create and connect MediaController</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVpx9RnLOunH6ggzu-PFOg.png" /></figure><ol><li>Create a media controller in the UI and connect to service</li><li>Show a loading indicator until the playback is ready</li><li>Play and pause the audio on button clicks.</li></ol><p>Your UI uses the media controller to send commands from your UI to the player within the session.</p><p>To create a MediaController, start by creating a SessionToken for the corresponding MediaSession</p><pre>val sessionToken =<br>  SessionToken(context, ComponentName(context, AudioPlayerService::class.java))</pre><p>Using this SessionToken to then build a MediaController connects the controller to the given session. This takes place asynchronously, <strong>so you should listen for the result and use it when available.</strong></p><pre>val controllerFuture =<br>  MediaController.Builder(context, sessionToken).buildAsync()<br>controllerFuture.addListener({<br>  // MediaController is available here with controllerFuture.get()<br>}, MoreExecutors.directExecutor())</pre><p>I have a helper method that creates the media controller asynchronously and notifies through a callback when it is ready.</p><pre>fun buildMediaController(context: Context, onControllerCreated: (MediaController) -&gt; Unit) {<br><br>    val url = &quot;https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3&quot;<br>    val mediaItem =<br>        MediaItem.Builder()<br>            .setMediaId(&quot;media-1&quot;)<br>            .setUri(url)<br>            .setMediaMetadata(<br>                MediaMetadata.Builder()<br>                    .setArtist(&quot;David Bowie&quot;)<br>                    .setTitle(&quot;Heroes&quot;)<br>                    .setArtworkUri(&quot;https://fastly.picsum.photos/id/997/536/354.jpg?hmac=xCNXWqL9v81aCTURDSIqYHbu34s-KcdT3jkRyzYZGtc&quot;.toUri())<br>                    .build()<br>            )<br>            .build()<br><br>    val sessionToken = SessionToken(context, ComponentName(context, AudioPlayerService::class.java))<br>    val controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()<br><br>    controllerFuture.addListener({<br>        val controller = controllerFuture.get()<br>        onControllerCreated(controller)<br>        controller.setMediaItem(mediaItem)<br>        controller.prepare()<br>        controller.play()<br>    }, ContextCompat.getMainExecutor(context))<br>}</pre><p>I used this method in the LaunchedEffect of AudioPlayerScreen like below</p><pre> LaunchedEffect(Unit) {<br>        buildMediaController(context = context, {<br>            mediaController = it<br>            mediaController?.addListener(object : Player.Listener {<br>                override fun onIsPlayingChanged(playing: Boolean) {<br>                    isPlaying = playing<br>                }<br>                override fun onPlaybackStateChanged(playbackState: Int) {<br>                    super.onPlaybackStateChanged(playbackState)<br>                    currentPlaybackState = playbackState<br>                }<br>            })<br>        })<br>    }</pre><p>Here, I am also observing the isPlaying and playbackState of the underlying player. But how this works? Read below :)</p><p><strong>Use a MediaController</strong></p><p>MediaController implements the Player interface, so you can use the commands defined in the interface to control playback of the connected MediaSession. This is to say that calling play() on a MediaController will send the command to the connected MediaSession, which will subsequently delegate the command to its underlying Player.</p><p>Now its the time to actually play and pause the player on button clicks</p><p>I modified the PlayerButton to accept a method that handles the clicks like below,</p><pre>@Composable<br>fun PlayerButton(playbackState: Int, isPlaying: Boolean, onPlayPauseClick: () -&gt; Unit) {<br>    Box(contentAlignment = Alignment.Center) {<br>        if (playbackState == Player.STATE_BUFFERING) {<br>            CircularProgressIndicator()<br>        } else {<br>            IconButton(modifier = Modifier.size(72.dp), onClick = onPlayPauseClick) {<br>                Icon(<br>                    imageVector = if (isPlaying) Icons.Filled.Pause<br>                    else Icons.Filled.PlayArrow,<br>                    contentDescription = &quot;Play Pause&quot;,<br>                    modifier = Modifier.fillMaxSize()<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>and modified its usage in the AudioPlayerScreen composable as below</p><pre>var mediaController by remember { mutableStateOf&lt;MediaController?&gt;(null) }<br>....<br><br>PlayerButton(playbackState = currentPlaybackState, isPlaying = isPlaying) {<br>     if (isPlaying) {<br>          mediaController?.pause()<br>      } else {<br>           mediaController?.play()<br>      }<br>}</pre><p>Here is the final output,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*pIwEq5m0vs3mCrwotncZGQ.gif" /></figure><p>We have to two way sync between media notification and UI. 👏 👏 👏</p><h3>Why This Architecture Works</h3><ul><li><strong>Player lives in the service</strong> (UI never owns playback)</li><li>System handles notification and lock-screen controls</li><li>Playback survives backgrounding and headset actions</li><li>Compose UI observes playback state; no guessing</li></ul><blockquote><em>This is the </em><strong><em>official Android-recommended approach</em></strong><em> for background audio.</em></blockquote><p>Here is the full code of AudioPlayerScreen.Kt</p><pre>package com.experiment.audioplayer.ui.theme<br><br>import android.content.ComponentName<br>import android.content.Context<br>import androidx.compose.foundation.Image<br>import androidx.compose.foundation.layout.Arrangement<br>import androidx.compose.foundation.layout.Box<br>import androidx.compose.foundation.layout.Column<br>import androidx.compose.foundation.layout.Spacer<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.foundation.layout.height<br>import androidx.compose.foundation.layout.padding<br>import androidx.compose.foundation.layout.size<br>import androidx.compose.foundation.shape.RoundedCornerShape<br>import androidx.compose.material.icons.Icons<br>import androidx.compose.material.icons.filled.Pause<br>import androidx.compose.material.icons.filled.PlayArrow<br>import androidx.compose.material3.CircularProgressIndicator<br>import androidx.compose.material3.Icon<br>import androidx.compose.material3.IconButton<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.LaunchedEffect<br>import androidx.compose.runtime.getValue<br>import androidx.compose.runtime.mutableIntStateOf<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.remember<br>import androidx.compose.runtime.setValue<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.draw.clip<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.layout.ContentScale<br>import androidx.compose.ui.platform.LocalContext<br>import androidx.compose.ui.res.painterResource<br>import androidx.compose.ui.unit.dp<br>import androidx.core.content.ContextCompat<br>import androidx.core.net.toUri<br>import androidx.media3.common.MediaItem<br>import androidx.media3.common.MediaMetadata<br>import androidx.media3.common.Player<br>import androidx.media3.session.MediaController<br>import androidx.media3.session.SessionToken<br>import com.experiment.audioplayer.R<br>import com.experiment.audioplayer.service.AudioPlayerService<br><br>@Composable<br>fun AudioPlayerScreen() {<br>    val context = LocalContext.current<br><br>    var isPlaying by remember { mutableStateOf(false) }<br>    var mediaController by remember { mutableStateOf&lt;MediaController?&gt;(null) }<br>    var currentPlaybackState by remember { mutableIntStateOf(Player.STATE_BUFFERING) }<br><br>    LaunchedEffect(Unit) {<br>        buildMediaController(context = context, {<br>            mediaController = it<br>            mediaController?.addListener(object : Player.Listener {<br>                override fun onIsPlayingChanged(playing: Boolean) {<br>                    isPlaying = playing<br>                }<br>                override fun onPlaybackStateChanged(playbackState: Int) {<br>                    super.onPlaybackStateChanged(playbackState)<br>                    currentPlaybackState = playbackState<br>                }<br>            })<br>        })<br>    }<br><br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(24.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br><br>        // Artwork<br>        Image(<br>            painter = painterResource(id = R.drawable.album_art),<br>            contentDescription = &quot;Album artwork&quot;,<br>            modifier = Modifier<br>                .size(220.dp)<br>                .clip(RoundedCornerShape(16.dp)),<br>            contentScale = ContentScale.Crop<br>        )<br><br>        Spacer(modifier = Modifier.height(24.dp))<br><br>        // Title<br>        Text(<br>            text = &quot;Heroes&quot;,<br>            style = MaterialTheme.typography.titleLarge<br>        )<br><br>        Text(<br>            text = &quot;David Bowie&quot;,<br>            style = MaterialTheme.typography.bodyMedium,<br>            color = Color.Gray<br>        )<br><br>        Spacer(modifier = Modifier.height(32.dp))<br><br>        // Controls<br>        PlayerButton(playbackState = currentPlaybackState, isPlaying = isPlaying) {<br>            if (isPlaying) {<br>                mediaController?.pause()<br>            } else {<br>                mediaController?.play()<br>            }<br>        }<br>    }<br>}<br><br>fun buildMediaController(context: Context, onControllerCreated: (MediaController) -&gt; Unit) {<br>    val url = &quot;https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3&quot;<br>    val sessionToken = SessionToken(context, ComponentName(context, AudioPlayerService::class.java))<br>    val mediaItem =<br>        MediaItem.Builder()<br>            .setMediaId(&quot;media-1&quot;)<br>            .setUri(url)<br>            .setMediaMetadata(<br>                MediaMetadata.Builder()<br>                    .setArtist(&quot;David Bowie&quot;)<br>                    .setTitle(&quot;Heroes&quot;)<br>                    .setArtworkUri(&quot;https://fastly.picsum.photos/id/997/536/354.jpg?hmac=xCNXWqL9v81aCTURDSIqYHbu34s-KcdT3jkRyzYZGtc&quot;.toUri())<br>                    .build()<br>            )<br>            .build()<br>    val controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()<br>    controllerFuture.addListener({<br>        val controller = controllerFuture.get()<br>        onControllerCreated(controller)<br>        controller.setMediaItem(mediaItem)<br>        controller.prepare()<br>        controller.play()<br>    }, ContextCompat.getMainExecutor(context))<br>}<br><br>@Composable<br>fun PlayerButton(playbackState: Int, isPlaying: Boolean, onPlayPauseClick: () -&gt; Unit) {<br>    Box(contentAlignment = Alignment.Center) {<br>        if (playbackState == Player.STATE_BUFFERING) {<br>            CircularProgressIndicator()<br>        } else {<br>            IconButton(modifier = Modifier.size(72.dp), onClick = onPlayPauseClick) {<br>                Icon(<br>                    imageVector = if (isPlaying) Icons.Filled.Pause<br>                    else Icons.Filled.PlayArrow,<br>                    contentDescription = &quot;Play Pause&quot;,<br>                    modifier = Modifier.fillMaxSize()<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>If this helped you understand background audio playback a little better, feel free to <strong>clap 👏 and share</strong> it with others building media apps in Compose. Clean playback architecture saves hours of debugging — hope this saves you some time. Happy coding 🎧</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88214b02266d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Dynamic Country Selector in Jetpack Compose]]></title>
            <link>https://medium.com/@janand1991/creating-a-dynamic-country-selector-in-jetpack-compose-06c358097794?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/06c358097794</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 11:56:27 GMT</pubDate>
            <atom:updated>2025-03-09T11:56:27.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qo23T1M4w5tyY3CvHu06OA.jpeg" /></figure><p>In Android development, one common UI feature you might need is a country selector. This often appears in forms or settings where users need to choose their country. In this blog post, we will explore how to create a dynamic country selector in Jetpack Compose. We’ll use a bottom sheet to display a list of countries fetched using Locale.getISOCountries(). When a user selects a country, it will update the displayed text in the main UI.</p><h3>The Problem</h3><p>We need to build a country selection component that:</p><ol><li>Displays a Placeholder that lets users know they need to select a country.</li><li>Shows a bottom sheet with a list of countries when clicked.</li><li>Updates the selected country on the main UI when the user selects an item from the list.</li></ol><p>Let’s break down the steps to implement this.</p><h3>Creating the CountryField Composable</h3><p>The CountryField composable is the key element here. This is where the user will interact with the UI. It contains the Text that displays the selected country, and it opens the bottom sheet when clicked.</p><p>Here’s how we implement it:</p><pre>@Composable<br>fun CountryField(<br>    modifier: Modifier = Modifier,<br>    country: Country? = null,<br>    onCountrySelected: (Country) -&gt; Unit = {}<br>) {<br>    var showCountriesBottomSheet by remember { mutableStateOf(false) }<br>    var selectedCountry: Country? by remember { mutableStateOf(country) }<br><br>    Row(modifier = modifier<br>        .fillMaxWidth()<br>        .clickable { showCountriesBottomSheet = !showCountriesBottomSheet }<br>        .padding(16.dp),<br>        verticalAlignment = Alignment.CenterVertically) {<br>        Text(text = selectedCountry?.displayText ?: &quot;\uD83C\uDFF4 Select Country&quot;)<br>    }<br><br>    if (showCountriesBottomSheet) {<br>        CountryBottomSheet(<br>            onDismiss = { showCountriesBottomSheet = false }) {<br>            CountrySelector(onCountrySelected = {<br>                selectedCountry = it<br>                onCountrySelected(it)<br>                showCountriesBottomSheet = false<br>            }, selectedCountry = selectedCountry)<br>        }<br>    }<br>}</pre><p>Here’s a breakdown of how this works:</p><ul><li><strong>State Management:</strong> Two states were used here, showCountriesBottomSheetto maintain the visibility of bottom sheet and selectedCountryto keep the selected country value.</li><li><strong>Click Event:</strong> When the Row is clicked, the showCountriesBottomSheet state toggles, and the bottom sheet appears.</li><li><strong>Country Selection:</strong> The CountrySelector composable inside the bottom sheet displays a list of countries, and when a country is selected, it updates the main Text with the selected country&#39;s name.</li></ul><p>When no country is selected, I displayed an empty flag along with ‘Select Country’ text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2Lv-iU12IlbQE1Ugxt7bg.png" /></figure><p>I’ve created a tiny Data class to keep the country iso code and display text as below,</p><pre>data class Country(val countryCode: String, val displayText: String)</pre><p>this displayText represents the flag emoji and country’s full name.</p><p>Bottom sheet shows the list of countries with flag,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP5QCYIMuQU65Buj2mehLw.png" /></figure><h3>Fetching the Country List: getCountries()</h3><p>The list of countries is fetched using the Locale.getISOCountries() method. This returns a list of ISO country codes. Using these codes, we can generate a list of Country objects, each containing the country’s name and flag emoji.</p><pre>fun getCountries(): ArrayList&lt;Country&gt; {<br>    val isoCountryCodes: Array&lt;String&gt; = Locale.getISOCountries()<br>    val countries: ArrayList&lt;Country&gt; = arrayListOf()<br><br>    for (countryCode in isoCountryCodes) {<br>        val locale = Locale(&quot;&quot;, countryCode)<br>        val countryName: String = locale.displayCountry<br>        val flagOffset = 0x1F1E6<br>        val asciiOffset = 0x41<br>        val firstChar = Character.codePointAt(countryCode, 0) - asciiOffset + flagOffset<br>        val secondChar = Character.codePointAt(countryCode, 1) - asciiOffset + flagOffset<br>        val flag = String(Character.toChars(firstChar)) + String(Character.toChars(secondChar))<br>        val displayText = &quot;$flag $countryName&quot;<br>        countries.add(Country(countryCode, displayText))<br>    }<br>    return countries<br>}</pre><p>The function getCountries() generates a list of Country objects, each containing:</p><ul><li><strong>Country Code:</strong> The ISO country code.</li><li><strong>Display Text:</strong> The country name with its corresponding flag emoji.</li></ul><h3>Displaying the Country List: CountrySelector</h3><p>The CountrySelector composable is responsible for displaying the list of countries. It fetches the country data and shows a loading spinner until the data is available. Once the data is ready, it displays the list of countries in a LazyColumn.</p><pre>@Composable<br>fun CountrySelector(onCountrySelected: (Country) -&gt; Unit = {},<br>                    selectedCountry: Country? = null) {<br>    var countries by remember { mutableStateOf&lt;List&lt;Country&gt;&gt;(emptyList()) }<br>    var isLoading by remember { mutableStateOf(true) }  // Loading state<br><br>    LaunchedEffect(Unit) {<br>        try {<br>            val result = withContext(Dispatchers.IO) {<br>                getCountries()  // Locale call<br>            }<br>            countries = result<br>        } catch (e: Exception) {<br>            countries = emptyList()<br>        } finally {<br>            isLoading = false  // Set loading state to false once the data is fetched<br>        }<br>    }<br><br>    if (isLoading) {<br>        // Show loading indicator while fetching data<br>        Box(<br>            modifier = Modifier.fillMaxSize(),<br>            contentAlignment = Alignment.Center<br>        ) {<br>            CircularProgressIndicator()<br>        }<br>    } else {<br>        // Display countries list once the data is fetched<br>        LazyColumn(modifier = Modifier.fillMaxSize()) {<br>            items(countries) { country -&gt;<br>                val backgroundColor = if (country.countryCode == selectedCountry?.countryCode) {<br>                    Color.LightGray<br>                } else {<br>                    Color.White<br>                }<br><br>                Row(modifier = Modifier<br>                    .fillMaxWidth().background(backgroundColor)<br>                    .clickable { onCountrySelected(country) }<br>                    .padding(16.dp),<br>                    verticalAlignment = Alignment.CenterVertically) {<br>                    Text(text = country.displayText)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Final Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DNIrQVfWnY4qC04Y02SinQ.gif" /><figcaption>Final result</figcaption></figure><h3>Enjoyed the Post?</h3><p>If you found this blog helpful, don’t forget to give it a clap! Your support helps me create more content and motivates me to keep sharing useful insights with the community. Feel free to share it with others who might benefit as well.</p><p>Thanks for reading, and I appreciate your support!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06c358097794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Dry Dates Here! A Guide to DatePickers in Jetpack Compose]]></title>
            <link>https://medium.com/@janand1991/no-dry-dates-here-a-guide-to-datepickers-in-jetpack-compose-14e23744bd4e?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e23744bd4e</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[datepicker]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 12:17:44 GMT</pubDate>
            <atom:updated>2024-09-26T12:56:26.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGfrCH39nJzymRN-o2yDog.jpeg" /></figure><p>Imagine you’re at a grocery store, staring at a bin full of dry dates, wondering which one to pick. Dark, sweet, slightly wrinkled — the perfect snack for a healthy treat. But wait, what if your task wasn’t just to pick the best dried fruit, but to also pick <em>a date</em> — as in the actual day, month, and year? Now, unless you’re really good at remembering the expiration dates on the packaging, you’d probably need some help from a handy calendar.</p><p>Well, that’s where Jetpack Compose comes to the rescue! No need to squint at the grocery label or fiddle with a physical calendar. Whether you’re picking dry dates for your snacks or an actual date for your app, there’s a picker for that! Let’s dive into the delightful world of Jetpack Compose DatePickers — where picking a date becomes just as easy as shopping for your favorite snack.</p><h4>Three Ways to Display a DatePicker</h4><p>Jetpack Compose offers a variety of ways to display DatePickers, so you can craft the best user experience for your app.</p><p>Let’s take a look at three popular methods:</p><ol><li>Docked</li></ol><p>2. Modal</p><p>3. Input Modal</p><h4>Docked DatePicker</h4><p>The <strong>Docked</strong> DatePicker is like having a calendar widget permanently embedded in your UI. It’s always visible and lets the user pick a date without any additional clicks or popups. This is great for scenarios where selecting a date is a primary action, like booking apps or reservation forms.</p><p>Here’s how you can implement a Docked DatePicker</p><pre><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun DockedDatePicker(modifier: Modifier = Modifier) {<br>    val datePickerState = rememberDatePickerState()<br>    val selectedDate = datePickerState.selectedDateMillis?.let {<br>        convertMillisToDate(it)<br>    } ?: &quot;&quot;<br><br>    Column(<br>        modifier = modifier<br>            .fillMaxWidth()<br>            .padding(12.dp),<br>        horizontalAlignment = Alignment.Start<br>    ) {<br>        OutlinedTextField(<br>            value = selectedDate,<br>            onValueChange = { },<br>            label = { Text(&quot;DOB&quot;) },<br>            readOnly = true,<br>            trailingIcon = {<br>                Icon(<br>                    imageVector = Icons.Default.DateRange,<br>                    contentDescription = &quot;Select date&quot;<br>                )<br>            },<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .height(64.dp)<br>        )<br>        DatePicker(<br>            state = datePickerState,<br>            showModeToggle = false,<br>            colors = DatePickerDefaults.colors(containerColor = Color(0xFFDDDCDF))<br>        )<br>    }<br>}<br><br>fun convertMillisToDate(millis: Long): String {<br>    val formatter = SimpleDateFormat(&quot;MM/dd/yyyy&quot;, Locale.getDefault())<br>    return formatter.format(Date(millis))<br>}</pre><ul><li>selectedDate captures the value of the selected date from the DatePickerState object and formats it using the convertMillisToDate function.</li><li>The selected date appears in the text field.</li><li>I have updated the background color of the DatePicker</li></ul><p>Here is the output!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*7ukXAwKE1Ba14mLAZYzoXg.gif" /></figure><h4>Modal DatePicker</h4><p>If you don’t want the DatePicker cluttering your screen, you can opt for the <strong>Modal DatePicker</strong>, which appears as a popup when triggered. This is perfect for apps where you want to conserve screen real estate but still allow users to pick a date when needed.</p><p>Here’s how you can implement a Modal DatePicker:</p><pre><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun ModalDatePicker(modifier: Modifier = Modifier) {<br>    val datePickerState = rememberDatePickerState()<br>    var showDatePicker by remember {<br>        mutableStateOf(false)<br>    }<br>    var selectedDate by remember {<br>        mutableStateOf(&quot;&quot;)<br>    }<br><br>    Column(<br>        modifier = modifier<br>            .fillMaxWidth()<br>            .padding(12.dp),<br>        horizontalAlignment = Alignment.Start<br>    ) {<br>        OutlinedTextField(<br>            value = selectedDate,<br>            onValueChange = { },<br>            label = { Text(&quot;DOB&quot;) },<br>            readOnly = true,<br>            trailingIcon = {<br>                IconButton(onClick = { showDatePicker = true }) {<br>                    Icon(<br>                        imageVector = Icons.Default.DateRange,<br>                        contentDescription = &quot;Select date&quot;<br>                    )<br>                }<br>            },<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .height(64.dp)<br>        )<br>        if (showDatePicker) {<br>            DatePickerModal(<br>                datePickerState = datePickerState,<br>                onDateSelected = { it?.let { selectedDate = convertMillisToDate(it) } }) {<br>                showDatePicker = false<br>            }<br>        }<br>    }<br>}<br><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun DatePickerModal(<br>    datePickerState: DatePickerState,<br>    onDateSelected: (Long?) -&gt; Unit,<br>    onDismiss: () -&gt; Unit<br>) {<br>    DatePickerDialog(<br>        onDismissRequest = onDismiss,<br>        confirmButton = {<br>            TextButton(onClick = {<br>                onDateSelected(datePickerState.selectedDateMillis)<br>                onDismiss()<br>            }) {<br>                Text(&quot;OK&quot;)<br>            }<br>        },<br>        dismissButton = {<br>            TextButton(onClick = onDismiss) {<br>                Text(&quot;Cancel&quot;)<br>            }<br>        }<br>    ) {<br>        DatePicker(state = datePickerState)<br>    }<br>}</pre><ul><li>The DatePickerModal composable function displays a modal date picker.</li><li>An OutlinedTextField with calendar icon</li><li>On clicking the icon, DatePickerModal will be shown</li><li>The selectedDate is communicated through onDateSelectedcallback.</li><li>On dismissing the modal, showDatePicker will be set to false.</li></ul><p>Here is the output!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*W8fcHi3j0H0nnI4Ibpso_w.gif" /></figure><h4>Input Modal DatePicker</h4><p>The <strong>Input Modal DatePicker</strong> combines a text field with a DatePicker popup. It gives users the flexibility to either type in a date manually or pick one from a popup calendar. This method is excellent for forms or when precision is key — just in case your user knows the date by heart!</p><p>Here’s how you can implement an Input Modal DatePicker:</p><pre><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun ModalDatePicker(modifier: Modifier = Modifier) {<br>    val datePickerState = rememberDatePickerState()<br>    var showDatePicker by remember {<br>        mutableStateOf(false)<br>    }<br>    var selectedDate by remember {<br>        mutableStateOf(&quot;&quot;)<br>    }<br><br>    Column(<br>        modifier = modifier<br>            .fillMaxWidth()<br>            .padding(12.dp),<br>        horizontalAlignment = Alignment.Start<br>    ) {<br>        OutlinedTextField(<br>            value = selectedDate,<br>            onValueChange = { },<br>            label = { Text(&quot;DOB&quot;) },<br>            readOnly = true,<br>            trailingIcon = {<br>                IconButton(onClick = { showDatePicker = true }) {<br>                    Icon(<br>                        imageVector = Icons.Default.DateRange,<br>                        contentDescription = &quot;Select date&quot;<br>                    )<br>                }<br>            },<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .height(64.dp)<br>        )<br>        if (showDatePicker) {<br>            DatePickerModalInput(<br>                datePickerState = datePickerState,<br>                onDateSelected = { it?.let { selectedDate = convertMillisToDate(it) } }) {<br>                showDatePicker = false<br>            }<br>        }<br>    }<br>}<br><br><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun DatePickerModalInput(<br>    datePickerState: DatePickerState,<br>    onDateSelected: (Long?) -&gt; Unit,<br>    onDismiss: () -&gt; Unit<br>) {<br><br>    DatePickerDialog(<br>        onDismissRequest = onDismiss,<br>        confirmButton = {<br>            TextButton(onClick = {<br>                onDateSelected(datePickerState.selectedDateMillis)<br>                onDismiss()<br>            }) {<br>                Text(&quot;OK&quot;)<br>            }<br>        },<br>        dismissButton = {<br>            TextButton(onClick = onDismiss) {<br>                Text(&quot;Cancel&quot;)<br>            }<br>        }<br>    ) {<br>        DatePicker(state = datePickerState)<br>    }<br>}</pre><ul><li>The DatePickerModalInput composable function displays an input modal date picker.</li><li>An OutlinedTextField with calendar icon</li><li>On clicking the icon, DatePickerModalInput will be shown</li><li>The selectedDate is communicated through onDateSelectedcallback.</li><li>On dismissing the modal, showDatePicker will be set to false.</li></ul><p>Here is the output!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*dyxlBDF3Yf_t7grJTaEIew.gif" /></figure><h3>Conclusion</h3><p>Each of these DatePicker methods comes with its own advantages. Whether you need a <strong>Docked</strong> option for always-visible date selection, a <strong>Modal</strong> to save space, or the flexibility of an <strong>Input Modal</strong>, Jetpack Compose has got you covered. So go ahead, pick a date (no dry fruit involved this time) and implement it in your app!</p><p>Read more at: <a href="https://developer.android.com/develop/ui/compose/components/datepickers">https://developer.android.com/develop/ui/compose/components/datepickers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e23744bd4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExoPlayer in Jetpack Compose: Ditch the XML, Play with Compose!]]></title>
            <link>https://medium.com/@janand1991/mastering-exoplayer-in-jetpack-compose-ditch-the-xml-play-with-compose-0ec9461d67b2?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ec9461d67b2</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[media3]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 09:33:22 GMT</pubDate>
            <atom:updated>2024-09-19T10:10:53.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1CWpM7VKFNDyPxFwKwr-w.jpeg" /></figure><p>Jetpack Compose is revolutionizing Android UI development, giving us the power to create beautiful, dynamic interfaces without touching a single line of XML!</p><p>But what if you could take this even further and build a video player using ExoPlayer, all within the Compose world?</p><p>Yes, it’s possible — and I’m here to show you how! In this post, we’ll dive into the exciting world of ExoPlayer, with no XML, just pure Compose magic.</p><p>Get ready to supercharge your media apps and bring your UIs to life with seamless video playback, powered entirely by Compose!”</p><h4><strong>Four simple steps</strong></h4><p>You just need to follow the 4 simple steps as mentioned below,</p><ol><li>Add dependencies</li><li>Create the player</li><li>Prepare the player</li><li>Dispose the player</li></ol><h4>Add Dependencies</h4><p>To get started, add a dependency on the ExoPlayer, UI, and Common modules of Jetpack Media3:</p><pre>implementation &quot;androidx.media3:media3-exoplayer:1.4.1&quot;<br>implementation &quot;androidx.media3:media3-ui:1.4.1&quot;<br>implementation &quot;androidx.media3:media3-common:1.4.1&quot;</pre><p>Make sure to replace 1.4.1 with your preferred version of the library. You can refer to the <a href="https://github.com/androidx/media/tree/release/RELEASENOTES.md">release notes</a> to see the latest version.</p><h4>Create the player</h4><p>With Media3, you can either use the included implementation of the Player interface, ExoPlayer, or you can build your own custom implementation.</p><p>The simplest way to create an ExoPlayer instance is as follows:</p><pre>val player = ExoPlayer.Builder(context).build()</pre><p>This player instance should be created in onCreate() lifecycle method of the Activity, Fragment, or Service where it lives.</p><p>You can further customize this <a href="https://developer.android.com/reference/androidx/media3/exoplayer/ExoPlayer.Builder">Builder</a> as required.</p><h4>Prepare the player</h4><p>This step is crucial as we are giving life to the player :).</p><p>This involves creating a mediaItem and setting it to the player. <strong>Remember not to prepare the player before it comes to the foreground.</strong></p><p>It is recommended to prepare the player in onStart() lifecycle method of the Activity.</p><pre>val mediaItem = MediaItem.Builder().setUri(videoUri)<br><br>val player = ExoPlayer.Builder(context).build().apply {<br>                setMediaItem(mediaItem)<br>                prepare()<br>             }</pre><h4>Dispose the player</h4><p>It’s important to call <a href="https://developer.android.com/reference/androidx/media3/common/Player#release()">release()</a> on your player to free up resources when the player is no longer needed. In Activity, it should be done in the onStop() lifecycle method.</p><p>Yes! you guessed it right. In Jetpack compose we can achieve this by implementing a <a href="https://developer.android.com/develop/ui/compose/side-effects#disposableeffect">DisposableEffect</a>.</p><p>Whenever the player composable is leaving from the composition, we should release the exoplayer instance.</p><pre>  val lifecycleOwner = LocalLifecycleOwner.current<br><br>  // Release the player when no longer needed<br>    DisposableEffect(<br>        lifecycleowner,<br>        effect = {<br>            onDispose { player.release() }<br>        }<br>    )</pre><h4>Output</h4><p>Wow! You just made an exoplayer with no XML!!. Here is the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*X3TqreQcOf63XFWo0Xe2cA.gif" /><figcaption>Compose Player</figcaption></figure><h4>Full source code</h4><p><em>MainActivity.kt</em></p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            ComposePlayerTheme {<br>                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -&gt;<br>                    PlayerScreen(<br>                        modifier = Modifier.padding(innerPadding)<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><em>PlayerScreen.kt</em></p><pre><br>@Composable<br>fun PlayerScreen(modifier: Modifier = Modifier) {<br>    val mediaItem =<br>        MediaItem.fromUri(Uri.parse(&quot;https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4&quot;))<br>    Box(modifier = modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {<br>        VideoPlayer(mediaItem = mediaItem)<br>    }<br>}</pre><p><em>VideoPlayer.kt</em></p><pre><br>@Composable<br>fun VideoPlayer(mediaItem: MediaItem) {<br>    // Create context from Compose<br>    val context = LocalContext.current<br><br>    val lifecycleOwner = LocalLifecycleOwner.current<br><br>    // Create and remember an ExoPlayer instance<br>    val exoPlayer = remember {<br>        ExoPlayer.Builder(context).build().apply {<br>            // Start playing the video automatically<br>            playWhenReady = true<br>        }<br>    }<br><br>    LaunchedEffect(exoPlayer, mediaItem) {<br>        // Create the MediaItem<br>        exoPlayer.addMediaItem(mediaItem)<br>        // Prepare the player<br>        exoPlayer.prepare()<br>    }<br><br>    val defaultPlayerView =<br>        remember {<br>            PlayerView(context).apply {<br>                player = exoPlayer<br>                // Enables playback controls (play, pause, etc.)<br>                useController = true  <br>            }<br>        }<br><br>    // Compose the UI with ExoPlayer<br>    // AndroidView for ExoPlayer&#39;s PlayerView<br>    AndroidView(<br>        factory = {<br>            defaultPlayerView.apply {<br>                setBackgroundColor(Color.BLACK)<br>            }<br>        },<br>        modifier = Modifier.fillMaxWidth()<br>    )<br><br>    // Release ExoPlayer when no longer needed<br>    DisposableEffect(lifecycleOwner) {<br>        onDispose {<br>            exoPlayer.release()<br>        }<br>    }<br>}</pre><p>That’s it! You’ve now seen how easy it is to implement ExoPlayer in Jetpack Compose without touching any XML.</p><p>💡 <a href="https://github.com/AnandJeyapal/ComposeVideoPlayer/blob/main/ComposePlayer/app/src/main/java/com/poc/composeplayer/player/VideoPlayer.kt">Github</a> Here is my project link to explore further.</p><p>If you found this guide helpful and learned something new today, I’d really appreciate your support! Don’t forget to give this post a few claps and share it with your fellow Android developers.</p><p>Your feedback and appreciation help me keep creating more content like this. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ec9461d67b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive UI in Jetpack Compose with WindowSizeClass]]></title>
            <link>https://medium.com/@janand1991/responsive-ui-in-jetpack-compose-with-windowsizeclass-a16487a76e20?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/a16487a76e20</guid>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 14:21:07 GMT</pubDate>
            <atom:updated>2024-09-16T14:23:15.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*j5pIbviM5VMQ8kuQmudY1w.png" /></figure><p>When building Android applications, creating a responsive user interface (UI) that adapts to different screen sizes is critical, especially with the growing variety of devices like foldables, tablets, and Chromebooks. Jetpack Compose makes this easier with the WindowSizeClass, which helps you adapt your UI based on different window sizes.</p><p>In this blog post, I’ll guide you through using WindowSizeClass to create a responsive layout in Jetpack Compose. I&#39;ll also provide sample code to help you implement it in your app.</p><h3>What is WindowSizeClass?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*7vtBjBCKia6wtRWkc2UDbA.png" /></figure><p>WindowSizeClass is part of the Material3 library and simplifies handling different window sizes. It categorizes screens into three sizes:</p><ul><li>Compact</li><li>Medium</li><li>Expanded</li></ul><p>These size classes allow you to design responsive UIs by defining layout changes depending on the available window size. Instead of using exact dimensions like dp or pixels, you can make your layout more flexible and adaptive.</p><h3>Setting up WindowSizeClass</h3><p>To use WindowSizeClass, you need to add the necessary dependencies to your build.gradle file:</p><pre>implementation &quot;androidx.compose.material3:material3:1.0.0&quot;</pre><p>Then, in your app’s MainActivity (or any other composable), you can define the window size class based on the current screen size.</p><h3>How to use WindowSizeClass</h3><p>The following steps show you how to implement WindowSizeClass to build a responsive layout.</p><h4>1. Get the Window Size Class</h4><p>First, you need to determine the WindowSizeClass of the current window. This can be done using the calculateWindowSizeClass method, which gives you a WindowSizeClass object representing the width and height classifications.</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            val windowSizeClass = calculateWindowSizeClass(this)<br>            MyComposeAppTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    MyResponsiveApp(windowSizeClass)<br>                }<br>            }<br>        }<br>    }</pre><pre>@Composable<br>fun MyResponsiveApp(windowSizeClass: WindowSizeClass) {<br>    when (windowSizeClass.widthSizeClass) {<br>        WindowWidthSizeClass.Compact -&gt; CompactScreen()<br>        WindowWidthSizeClass.Medium -&gt; MediumScreen()<br>        WindowWidthSizeClass.Expanded -&gt; ExpandedScreen()<br>    }<br>}</pre><p>In the above code, WindowWidthSizeClass is used to handle the width of the screen. You can adjust the layout based on whether the screen width is compact, medium, or expanded.</p><h4>2. Display Different UIs Based on Window Size</h4><p>Now let’s create different composables for each size class. For example, you can show a different layout for compact, medium, and expanded sizes:</p><pre>@Composable<br>fun CompactScreen() {<br>    Text(text = &quot;Compact Screen&quot;, style = MaterialTheme.typography.h6)<br>}<br><br>@Composable<br>fun MediumScreen() {<br>    Column {<br>        Text(text = &quot;Medium Screen&quot;, style = MaterialTheme.typography.h5)<br>        // Add more content for medium screens<br>    }<br>}<br><br>@Composable<br>fun ExpandedScreen() {<br>    Row {<br>        Text(text = &quot;Expanded Screen&quot;, style = MaterialTheme.typography.h4)<br>        // Add more content for expanded screens<br>    }<br>}</pre><p>The CompactScreen, MediumScreen, and ExpandedScreen composables provide different layouts for different screen sizes. In this simple example, I used Text with different styles, but you can define more complex UIs such as sidebars, dual panels, or grid layouts for larger screen sizes.</p><h4>Conclusion</h4><p>Using WindowSizeClass in Jetpack Compose helps you adapt your UI to different screen sizes in a simple and elegant way. By focusing on size classes (compact, medium, expanded), you can build responsive designs without hard-coding for specific dimensions.</p><p>Key takeaways:</p><ul><li><strong>Compact</strong> is for smaller phones.</li><li><strong>Medium</strong> is for large phones or small tablets.</li><li><strong>Expanded</strong> is for large tablets, foldable devices, or desktop-like screens.</li></ul><p>Try out the WindowSizeClass in your next Compose project and see how easy it becomes to build layouts that work across multiple screen sizes!</p><p>Happy coding! 🎨</p><p>Read more at: <a href="https://developer.android.com/develop/ui/compose/layouts/adaptive/window-size-classes">https://developer.android.com/develop/ui/compose/layouts/adaptive/window-size-classes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a16487a76e20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing ExoPlayer Using Android Media3 — Part II]]></title>
            <link>https://medium.com/@janand1991/implementing-exoplayer-using-android-media3-part-ii-f83c7aa430b4?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83c7aa430b4</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-tips-and-tricks]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 11:29:30 GMT</pubDate>
            <atom:updated>2024-09-08T11:59:41.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WszTr5yd3GtBjmXvqVi9-Q.jpeg" /></figure><h3>Implementing ExoPlayer Using Android Media3 — Part II</h3><p>In the <a href="https://medium.com/@janand1991/implementing-exoplayer-using-android-media3-part-i-c37ed3cbfd11">first part</a> of this series, we explored the initial setup and basic implementation of ExoPlayer using the Android Media3 library, creating a solid foundation for media playback in your app. While the default controls provided by ExoPlayer are functional, they may not always align with your app’s design or user experience goals.</p><p>In this second part, we will delve into customizing these controls, allowing you to tailor the media playback interface to better suit your application’s unique style and functionality requirements.</p><p>From modifying the layout of the player controls to handling custom behaviors programmatically, this guide will equip you with the knowledge to enhance your media player’s user interface and interaction.</p><h4>First things first — Default controller</h4><p>When you’re done with the initial implementation, the default controller would look like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0xLP8lFRDsofpjgmXmxdw.png" /></figure><p>Three things to notice here,</p><ol><li><strong>Center controls</strong> consist of prev, next, play, pause, forward and rewind actions.</li><li><strong>Seekbar </strong>which shows the current progress of the video.</li><li><strong>Bottom controls</strong> consist of position, duration and settings actions.</li></ol><h4>Where are these controls?</h4><p>When instantiating a newPlayerView , it takes the controls from PlayerControlView .</p><p>This PlayerControlView inflates a layout called exo_player_control_view.xml which looks like below,</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>  ....<br>  &lt;!-- Center controls --&gt;<br>  &lt;LinearLayout<br>      android:id=&quot;@id/exo_center_controls&quot;<br>      android:layout_width=&quot;wrap_content&quot;<br>      android:layout_height=&quot;wrap_content&quot;<br>      android:layout_gravity=&quot;center&quot;<br>      android:background=&quot;@android:color/transparent&quot;<br>      android:gravity=&quot;center&quot;<br>      android:padding=&quot;@dimen/exo_styled_controls_padding&quot;<br>      android:clipToPadding=&quot;false&quot;<br>      android:layoutDirection=&quot;ltr&quot;&gt;<br><br>    &lt;ImageButton android:id=&quot;@id/exo_prev&quot;<br>        style=&quot;@style/ExoStyledControls.Button.Center.Previous&quot;/&gt;<br><br>    &lt;include layout=&quot;@layout/exo_player_control_rewind_button&quot; /&gt;<br><br>    &lt;ImageButton android:id=&quot;@id/exo_play_pause&quot;<br>        style=&quot;@style/ExoStyledControls.Button.Center.PlayPause&quot;/&gt;<br><br>    &lt;include layout=&quot;@layout/exo_player_control_ffwd_button&quot; /&gt;<br><br>    &lt;ImageButton android:id=&quot;@id/exo_next&quot;<br>        style=&quot;@style/ExoStyledControls.Button.Center.Next&quot;/&gt;<br><br>  &lt;/LinearLayout&gt;<br><br>...<br><br>&lt;!-- Bottom bar --&gt;<br>&lt;FrameLayout android:id=&quot;@id/exo_bottom_bar&quot;<br>      android:layout_width=&quot;match_parent&quot;<br>      android:layout_height=&quot;@dimen/exo_styled_bottom_bar_height&quot;<br>      android:layout_marginTop=&quot;@dimen/exo_styled_bottom_bar_margin_top&quot;<br>      android:layout_gravity=&quot;bottom&quot;<br>      android:background=&quot;@color/exo_bottom_bar_background&quot;<br>      android:layoutDirection=&quot;ltr&quot;&gt;<br><br>    &lt;LinearLayout android:id=&quot;@id/exo_time&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:paddingStart=&quot;@dimen/exo_styled_bottom_bar_time_padding&quot;<br>        android:paddingEnd=&quot;@dimen/exo_styled_bottom_bar_time_padding&quot;<br>        android:paddingLeft=&quot;@dimen/exo_styled_bottom_bar_time_padding&quot;<br>        android:paddingRight=&quot;@dimen/exo_styled_bottom_bar_time_padding&quot;<br>        android:layout_gravity=&quot;center_vertical|start&quot;<br>        android:layoutDirection=&quot;ltr&quot;&gt;<br><br>      &lt;TextView android:id=&quot;@id/exo_position&quot;<br>          style=&quot;@style/ExoStyledControls.TimeText.Position&quot;/&gt;<br><br>      &lt;TextView<br>          style=&quot;@style/ExoStyledControls.TimeText.Separator&quot;/&gt;<br><br>      &lt;TextView android:id=&quot;@id/exo_duration&quot;<br>          style=&quot;@style/ExoStyledControls.TimeText.Duration&quot;/&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>    &lt;LinearLayout android:id=&quot;@id/exo_basic_controls&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center_vertical|end&quot;<br>        android:layoutDirection=&quot;ltr&quot;&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_vr&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.VR&quot;/&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_shuffle&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.Shuffle&quot;/&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_repeat_toggle&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.RepeatToggle&quot;/&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_subtitle&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.CC&quot;/&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_settings&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.Settings&quot;/&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_fullscreen&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.FullScreen&quot;/&gt;<br><br>      &lt;ImageButton android:id=&quot;@id/exo_overflow_show&quot;<br>          style=&quot;@style/ExoStyledControls.Button.Bottom.OverflowShow&quot;/&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>    &lt;HorizontalScrollView android:id=&quot;@id/exo_extra_controls_scroll_view&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center_vertical|end&quot;<br>        android:visibility=&quot;invisible&quot;&gt;<br><br>      &lt;LinearLayout android:id=&quot;@id/exo_extra_controls&quot;<br>          android:layout_width=&quot;wrap_content&quot;<br>          android:layout_height=&quot;wrap_content&quot;<br>          android:layoutDirection=&quot;ltr&quot;&gt;<br><br>        &lt;ImageButton android:id=&quot;@id/exo_overflow_hide&quot;<br>            style=&quot;@style/ExoStyledControls.Button.Bottom.OverflowHide&quot;/&gt;<br><br>      &lt;/LinearLayout&gt;<br><br>    &lt;/HorizontalScrollView&gt;<br><br>  &lt;/FrameLayout&gt;<br><br>&lt;!-- Seek bar --&gt;<br>&lt;View android:id=&quot;@id/exo_progress_placeholder&quot;<br>      android:layout_width=&quot;match_parent&quot;<br>      android:layout_height=&quot;@dimen/exo_styled_progress_layout_height&quot;<br>      android:layout_gravity=&quot;bottom&quot;<br>      android:layout_marginBottom=&quot;@dimen/exo_styled_progress_margin_bottom&quot;/&gt;</pre><p>The drawables used by PlayerControlView can be overridden by drawables with the same names defined in your application. Note that these icons will be the same across all usages of PlayerView/PlayerControlView in your app.</p><p>The drawables that can be overridden are:</p><ul><li><strong>exo_styled_controls_play</strong> - The play icon.</li><li><strong>exo_styled_controls_pause</strong> - The pause icon.</li><li><strong>exo_styled_controls_rewind</strong> - The background of rewind icon.</li><li><strong>exo_styled_controls_fastforward</strong> - The background of fast forward icon.</li><li><strong>exo_styled_controls_previous</strong> - The previous icon.</li><li><strong>exo_styled_controls_next</strong> - The next icon.</li><li><strong>exo_styled_controls_repeat_off</strong> - The repeat icon for <a href="https://developer.android.com/reference/androidx/media3/common/Player#REPEAT_MODE_OFF()">REPEAT_MODE_OFF</a>.</li><li><strong>exo_styled_controls_repeat_one</strong> - The repeat icon for <a href="https://developer.android.com/reference/androidx/media3/common/Player#REPEAT_MODE_ONE()">REPEAT_MODE_ONE</a>.</li><li><strong>exo_styled_controls_repeat_all</strong> - The repeat icon for <a href="https://developer.android.com/reference/androidx/media3/common/Player#REPEAT_MODE_ALL()">REPEAT_MODE_ALL</a>.</li><li><strong>exo_styled_controls_shuffle_off</strong> - The shuffle icon when shuffling is disabled.</li><li><strong>exo_styled_controls_shuffle_on</strong> - The shuffle icon when shuffling is enabled.</li><li><strong>exo_styled_controls_vr</strong> - The VR icon.</li><li><strong>exo_styled_controls_fullscreen_enter</strong> - The fullscreen icon for when the player is minimized.</li><li><strong>exo_styled_controls_fullscreen_exit</strong> - The fullscreen icon for when the player is in fullscreen mode.</li></ul><p>Read more about the customization <a href="https://developer.android.com/media/media3/ui/playerview#overriding-drawables"><em>here</em></a></p><h4>Advanced Customization</h4><p>Let’s assume you want to <strong>hide the bottom bar</strong> completely, and show the time information at the corners of the seebar like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pBLuXXzs0s-1MpN5sMbdw.png" /></figure><p>This can be achieved by keeping your customized layout named exo_player_control_view.xml in your application’s res/layout folder like below,</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;merge xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br><br>    &lt;View android:id=&quot;@id/exo_controls_background&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:background=&quot;@color/exo_black_opacity_60&quot;/&gt;<br><br>    &lt;!-- Customized Seekbar with time line--&gt;<br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;bottom&quot;<br>        android:paddingHorizontal=&quot;8dp&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@id/exo_position&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:paddingEnd=&quot;8dp&quot;<br>            style=&quot;@style/ExoStyledControls.TimeText.Position&quot;/&gt;<br><br>        &lt;androidx.media3.ui.DefaultTimeBar<br>            android:id=&quot;@id/exo_progress&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;@dimen/exo_styled_progress_layout_height&quot;<br>            android:layout_weight=&quot;1&quot;<br>            app:bar_gravity=&quot;center&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@id/exo_duration&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:paddingStart=&quot;8dp&quot;<br>            style=&quot;@style/ExoStyledControls.TimeText.Duration&quot;/&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;LinearLayout<br>        android:id=&quot;@id/exo_center_controls&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:background=&quot;@android:color/transparent&quot;<br>        android:gravity=&quot;center&quot;<br>        android:padding=&quot;@dimen/exo_styled_controls_padding&quot;<br>        android:clipToPadding=&quot;false&quot;<br>        android:layoutDirection=&quot;ltr&quot;&gt;<br><br>        &lt;ImageButton android:id=&quot;@id/exo_prev&quot;<br>            style=&quot;@style/ExoStyledControls.Button.Center.Previous&quot;/&gt;<br><br>        &lt;include layout=&quot;@layout/exo_player_control_rewind_button&quot; /&gt;<br><br>        &lt;ImageButton android:id=&quot;@id/exo_play_pause&quot;<br>            style=&quot;@style/ExoStyledControls.Button.Center.PlayPause&quot;/&gt;<br><br>        &lt;include layout=&quot;@layout/exo_player_control_ffwd_button&quot; /&gt;<br><br>        &lt;ImageButton android:id=&quot;@id/exo_next&quot;<br>            style=&quot;@style/ExoStyledControls.Button.Center.Next&quot;/&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>&lt;/merge&gt;</pre><h4>Final Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PP0Yrzto9WXWgJ8fMHe9yg.png" /></figure><h4>Different controller layouts for different exo players</h4><p>Assume your application has two player views in two different screens.</p><p>To have different customized controllers for both player views ,</p><p><strong><em>app: controller_layout_id</em></strong> will help.</p><p>Just keep two customized layouts in <a href="https://developer.android.com/reference/androidx/media3/common/Player#REPEAT_MODE_OFF()">res/layout</a> folder and specify them through <strong><em>app: controller_layout_id </em></strong>like below,</p><pre>&lt;androidx.media3.ui.PlayerView<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:id=&quot;@+id/player_view&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    app:controller_layout_id=&quot;🚀🚀@layout/your_own_custom_controller🚀🚀&quot; /&gt;</pre><p>In this blog, we have taken a deep dive into customizing Media3 ExoPlayer for Android, building upon the foundational knowledge covered in the first blog. By leveraging these customization techniques, you can create a more engaging and responsive media player tailored to the specific needs of your application.</p><p>As you continue to refine and expand your implementation, keep in mind the importance of balancing functionality with user experience. Testing across different devices and scenarios will ensure that your media player remains robust and efficient. I hope this series has provided you with valuable insights and practical guidance for harnessing the full potential of Media3 ExoPlayer in your Android projects. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83c7aa430b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing ExoPlayer Using Android Media3 — Part I]]></title>
            <link>https://medium.com/@janand1991/implementing-exoplayer-using-android-media3-part-i-c37ed3cbfd11?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37ed3cbfd11</guid>
            <category><![CDATA[media3]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-tips-and-tricks]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 09:23:46 GMT</pubDate>
            <atom:updated>2024-07-29T09:24:22.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wAPZpHowNRkppQFzpRBydQ.png" /></figure><h3>Implementing ExoPlayer Using Android Media3 — Part I</h3><p>Android’s Media3 library is the evolution of the previous ExoPlayer library, integrating it more closely with the Jetpack suite and offering enhanced features and flexibility.</p><p>This guide will walk you through the steps to implement ExoPlayer using the Android Media3 library.</p><h4>Setting up Project</h4><p>First, create a new Android project or open an existing one in Android Studio. Ensure that you have the required dependencies added to your build.gradle file as mentioned below.</p><pre>dependencies {<br>    implementation &#39;androidx.media3:media3-exoplayer:1.0.0-beta02&#39;<br>    implementation &#39;androidx.media3:media3-ui:1.0.0-beta02&#39;<br>}</pre><h4>Setting up AndroidManifest</h4><p>Make sure you have added android.permission.INTERNET permission in your manifest file as we are going to play the video from a network source.</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><h4>Design the Layout</h4><p>Create a layout file for your activity, activity_main.xml, and add a PlayerView to display the video.</p><pre>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;androidx.media3.ui.PlayerView<br>        android:id=&quot;@+id/player_view&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_centerInParent=&quot;true&quot; /&gt;<br><br>&lt;/RelativeLayout&gt;</pre><h4>Initialize the ExoPlayer</h4><p>In your MainActivity, initialize ExoPlayer and set it up with the PlayerView.</p><pre>import android.net.Uri<br>import android.os.Bundle<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.media3.common.MediaItem<br>import androidx.media3.exoplayer.ExoPlayer<br>import androidx.media3.ui.PlayerView<br><br>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var player: ExoPlayer<br>    private lateinit var playerView: PlayerView<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        // Initialize the PlayerView<br>        playerView = findViewById(R.id.player_view)<br><br>        // Initialize the ExoPlayer<br>        player = ExoPlayer.Builder(this).build()<br>        playerView.player = player<br><br>        // Prepare media item<br>        val mediaItem = MediaItem.fromUri(Uri.parse(&quot;https://www.example.com/media.mp4&quot;))<br>        player.setMediaItem(mediaItem)<br>        player.prepare()<br>        player.play()<br>    }<br><br>    override fun onStop() {<br>        super.onStop()<br>        player.release()<br>    }<br>}</pre><h4>Handle Lifecycle Events</h4><p>To ensure proper resource management, handle the player lifecycle by releasing the player in onStop or onDestroy and re-initializing it if necessary.</p><pre>override fun onStop() {<br>    super.onStop()<br>    player.release()<br>}</pre><p>For more complex use cases, consider pausing the player in onPause and resuming it in onResume.</p><pre>override fun onPause() {<br>    super.onPause()<br>    player.pause()<br>}<br><br>override fun onResume() {<br>    super.onResume()<br>    player.play()<br>}</pre><h4>Result</h4><p>Hooray!! You’ve implemented the basic video player, grab a coffee ☕ and be proud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dURl4qyQnZFS4mHEa3r_VQ.png" /></figure><h4>Conclusion</h4><p>Implementing ExoPlayer with Android Media3 provides a robust and flexible media playback solution for your Android apps. By following the steps outlined in this guide, you can set up a basic functional media player. I will cover the further customization of controls and enhancements in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37ed3cbfd11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Device Orientation Detection in Jetpack Compose]]></title>
            <link>https://medium.com/@janand1991/mastering-device-orientation-detection-in-jetpack-compose-7bedf4679e9b?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bedf4679e9b</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Wed, 22 May 2024 09:54:41 GMT</pubDate>
            <atom:updated>2024-05-23T07:47:51.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qOD9ByGR9PZlefhjQnTCg.jpeg" /></figure><p>Let’s assume you fixed the screen’s orientation to portrait or landscapelike below,</p><pre>activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT</pre><p>Then <a href="https://medium.com/@janand1991/mastering-screen-orientation-detection-in-jetpack-compose-a89658dfa50f">this solution</a> will not work and LocalConfiguration.current.orientation will always return Configuration.ORIENTATION_PORTRAIT even the user rotated the device horizontally.</p><p>Because the screen orientation is fixed to portrait, not the <strong>device orientation.</strong></p><p>In this blog post, we’ll delve into how to detect device orientation in Android using the OrientationListener.</p><h3>What is OrientationListener?</h3><p>OrientationListener is a class provided by the Android framework that allows developers to monitor changes in device orientation. By registering an OrientationListener with the system, your app can receive updates whenever the device orientation changes, such as when the user rotates their device from portrait to landscape or vice versa.</p><h3>Implementing Orientation Detection</h3><p>Let’s start by creating a composable that sets up an OrientationEventListener and displays different content based on the orientation.</p><h3>Step 1: Create the OrientationListener</h3><p>First, we need to create an OrientationEventListener through a DisposableEffect that will notify us when the device&#39;s orientation changes.</p><pre>@Composable<br>fun DeviceOrientationListener(applicationContext: Context, onOrientationChange: (DeviceOrientation) -&gt; Unit) {<br>  <br>DisposableEffect(Unit) {<br>    <br>  val orientationEventListener = object : OrientationEventListener(applicationContext) {<br>       override fun onOrientationChanged(orientation: Int) {<br>          if (orientation &gt;= 350 || orientation &lt; 10) {<br>             onOrientationChange(DeviceOrientation.DEVICE_ORIENTATION_PORTRAIT)<br>          } else if (orientation in 80..159) {<br>             onOrientationChange(DeviceOrientation.DEVICE_ORIENTATION_REVERSE_LANDSCAPE)<br>          } else if (orientation in 200..289) {<br>             onOrientationChange(DeviceOrientation.DEVICE_ORIENTATION_LANDSCAPE)<br>          }<br>       }<br>    }<br>  orientationEventListener.enable()<br><br>  // Disable the event onDispose<br>  onDispose {<br>     orientationEventListener.disable()<br>  }<br><br> }<br>}</pre><h3>Step 2: Create the Composable Function</h3><p>Next, we’ll create a composable function that sets up the OrientationEventListener and reacts to orientation changes.</p><pre>import android.content.Context<br>import androidx.compose.foundation.layout.*<br>import androidx.compose.material.*<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.platform.LocalContext<br>import androidx.compose.ui.unit.dp<br><br>@Composable<br>fun OrientationAwareContent() {<br>    val context = LocalContext.current<br>    var orientation by remember { mutableStateOf(DeviceOrientation.DEVICE_ORIENTATION_PORTRAIT) }<br><br>    val applicationContext = LocalContext.current.applicationContext<br>    DeviceOrientationListener(applicationContext) { orientation = it } <br><br>    if (orientation == DeviceOrientation.DEVICE_ORIENTATION_LANDSCAPE) {<br>        // Content to show in landscape mode<br>        LandscapeContent()<br>    } else {<br>        // Content to show in portrait mode<br>        PortraitContent()<br>    }<br>}<br><br>@Composable<br>fun PortraitContent() {<br>    Box(<br>        modifier = Modifier.fillMaxSize(),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Text(text = &quot;Portrait Mode&quot;, style = MaterialTheme.typography.h4)<br>    }<br>}<br>@Composable<br>fun LandscapeContent() {<br>    Box(<br>        modifier = Modifier.fillMaxSize(),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Text(text = &quot;Landscape Mode&quot;, style = MaterialTheme.typography.h4)<br>    }<br>}</pre><h3>Step 3: Handling Orientation Changes</h3><p>In our OrientationAwareContent composable, we initialize the DeviceOrientationListener and enable it when the composable enters the composition. We disable the listener when the composable leaves the composition to avoid memory leaks. (That’s the beauty of DisposableEffect)</p><p>We use the orientation state to keep track of the current orientation and display different content based on whether the device is in portrait or landscape mode.</p><h3>Step 4: Creating the Main Activity</h3><p>Finally, we set up our MainActivity to display the OrientationAwareContent composable.</p><pre>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import androidx.compose.material.*<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.tooling.preview.Preview<br>import com.example.orientationlistener.ui.theme.OrientationListenerTheme<br><br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            OrientationListenerTheme {<br>                OrientationAwareContent()<br>            }<br>        }<br>    }<br>}<br>@Preview(showBackground = true)<br>@Composable<br>fun DefaultPreview() {<br>    OrientationListenerTheme {<br>        OrientationAwareContent()<br>    }<br>}</pre><h3>Conclusion</h3><p>Detecting and handling device orientation changes in Jetpack Compose is straightforward with the OrientationEventListener. By setting up an OrientationEventListener within a composable and responding to orientation changes, we can create responsive and adaptive UI layouts that enhance the user experience.</p><p>This approach ensures that our app reacts dynamically to orientation changes, providing a seamless and engaging user experience. Try integrating this into your Jetpack Compose project and see how it improves your app’s responsiveness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bedf4679e9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Screen Orientation Detection in Jetpack Compose]]></title>
            <link>https://medium.com/@janand1991/mastering-screen-orientation-detection-in-jetpack-compose-a89658dfa50f?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/a89658dfa50f</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 12:25:14 GMT</pubDate>
            <atom:updated>2024-05-22T09:55:56.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*G-zftaybnQjb0z-fMnIzZg.jpeg" /></figure><p>In the realm of modern app development, creating user interfaces that adapt seamlessly to various screen orientations is paramount. Whether your users prefer portrait or landscape mode, ensuring your app looks and behaves appropriately is crucial for a polished user experience. In this blog post, we’ll explore how to leverage Jetpack Compose, Google’s modern UI toolkit for Android, to detect and respond to changes in screen orientation with finesse.</p><h3>Why detect Screen orientation?</h3><p>Understanding screen orientation is crucial for creating user interfaces that adapt to different screen sizes and orientations. By detecting whether a device is in portrait or landscape mode, you can optimize your app’s layout, improve readability, and enhance user interaction</p><h3>Three steps to listen and react</h3><p>Here’s a step-by-step guide to detecting screen orientation in Jetpack Compose:</p><ol><li><strong>Access Configuration</strong>: In your Composable function, access the device’s configuration using the LocalConfiguration.current property.</li><li><strong>Retrieve Orientation</strong>: Retrieve the orientation from the configuration using the orientation property.</li><li><strong>Handle Orientation</strong>: Based on the orientation, adjust your UI layout or perform any necessary actions.</li></ol><h3>Example Implementation 🚀</h3><p>Let’s demonstrate how to detect screen orientation with a simple example</p><pre>import androidx.compose.foundation.layout.Column<br>import androidx.compose.material.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.platform.LocalConfiguration<br>import androidx.compose.ui.text.style.TextAlign<br>import androidx.compose.ui.tooling.preview.Preview<br><br>@Composable<br>fun OrientationExample() {<br>    val configuration = LocalConfiguration.current<br>    val orientation = configuration.orientation<br>    Column {<br>        Text(<br>            text = if (orientation == Configuration.ORIENTATION_PORTRAIT) <br>                      &quot;Portrait&quot; else &quot;Landscape&quot;,<br>            textAlign = TextAlign.Center<br>        )<br>    }<br>}<br><br>@Preview(showBackground = true)<br>@Composable<br>fun PreviewOrientationExample() {<br>    OrientationExample()<br>}</pre><p>In this example, we create a Text composable displaying the current screen orientation based on the value retrieved from LocalConfiguration.current.orientation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ZGZLv7MwCFliIPpzazIEhw.png" /><figcaption>Application in portrait mode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*DG0USbtcqP05AdHTKjYusw.png" /><figcaption>Application in landscape mode</figcaption></figure><h3>Best Practices</h3><ul><li><strong>Responsive Layouts</strong>: Use screen orientation detection to create responsive layouts that adapt to different screen orientations.</li><li><strong>Optimized UI</strong>: Adjust font sizes, padding, and spacing dynamically to ensure optimal readability and usability in both portrait and landscape modes.</li><li><strong>Testing</strong>: thoroughly test your app in both orientations to identify and fix any layout or usability issues</li></ul><h3>Conclusion</h3><p>Detecting screen orientation is essential for delivering a seamless user experience in mobile apps. With Jetpack Compose, the process becomes straightforward and intuitive. By leveraging the LocalConfiguration composition local, you can easily adapt your UI to different screen orientations, providing users with a consistent and enjoyable interaction experience across various devices.</p><p>Incorporate orientation detection into your Jetpack Compose projects today and unlock the full potential of dynamic and responsive user interfaces.</p><h3>Follow-up</h3><p>Let’s assume you fixed the screen’s orientation to portrait like below,</p><pre>activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT</pre><p>Then the above solution will not work and LocalConfiguration.current.orientation will always return Configuration.ORIENTATION_PORTRAIT even the user rotated the device horizontally.</p><p>Because the screen orientation is fixed to portrait, not the <strong>device orientation </strong>💡</p><p>How to detect device orientation? Will cover that in my <a href="https://medium.com/@janand1991/mastering-device-orientation-detection-in-jetpack-compose-7bedf4679e9b">next blog</a>. ✍️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a89658dfa50f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to DisposableEffect in Compose]]></title>
            <link>https://medium.com/@janand1991/disposableeffect-in-action-739e83af347f?source=rss-b6e535d55063------2</link>
            <guid isPermaLink="false">https://medium.com/p/739e83af347f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[side-effects]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Anand Jeyapal]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 13:19:37 GMT</pubDate>
            <atom:updated>2024-02-27T06:33:17.897Z</atom:updated>
            <content:encoded><![CDATA[<pre>// If `key1 or key2` changes, dispose and reset the effect<br>DisposableEffect(key1, key2) {<br>    doStuff()<br>    // When the effect leaves the Composition, remove the observer<br>    onDispose {<br>      doCleanup()<br>    }<br>}</pre><h4>DisposableEffect is one of the side effects in Jetpack compose. It has an additional method called ‘onDispose’</h4><p>This <em>onDispose</em> method will be called in the following situations,</p><ol><li>When the keys of DisposableEffect are changed.</li><li>When the enclosing composable leaves the composition.</li></ol><blockquote>Let’s create a <em>Composable</em> which shows a Button at the center of a column.</blockquote><pre>@Composable<br>fun Screen() {<br>    Column(<br>    Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center,<br>    horizontalAlignment = Alignment.CenterHorizontally<br>) {<br>       Button(onClick = {  }) {<br>            Text(“I was clicked 0 times”)<br>        }<br>    }<br>}</pre><blockquote>Create a mutableState for the count which is displayed in Button composable.</blockquote><pre>var count by remember { mutableIntStateOf(0)}</pre><pre>Button(onClick = {  }) {<br>    Text(&quot;I was clicked $count times&quot;)<br>}</pre><blockquote>Update the onClick of the Button. On clicking the button, count will be increased like below.</blockquote><pre>Button(onClick = { count += 1 }) {<br>…</pre><p>Since the state is changed, recomposition would happen and it re-renders the Button composable.</p><blockquote>Now create a disposable effect that listens this <em>count</em></blockquote><pre>        // If `count` changes, dispose and reset the effect<br>        DisposableEffect(count) {<br>            Log.d(&quot;AAA&quot;, &quot;I am doing some stuff&quot;)<br>            // When the effect leaves the Composition, run onDispose<br>            onDispose {<br>              Log.d(&quot;AAA&quot;, &quot;I am cleaning the mess&quot;)<br>            }<br>        }</pre><blockquote>The final code would look like below</blockquote><pre>@Composable<br>fun Screen() {<br>    var count by remember { mutableIntStateOf(0) }<br>    Column(<br>        Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Button(onClick = { count += 1 }) {<br>            Text(&quot;I was clicked $count times&quot;)<br>        }<br>        // If `textToDisplay` changes, dispose and reset the effect<br>        DisposableEffect(count) {<br>            Log.d(&quot;AAA&quot;, &quot;I am doing some stuff&quot;)<br>            // When the effect leaves the Composition, run onDispose<br>            onDispose {<br>                Log.d(&quot;AAA&quot;, &quot;I am cleaning the mess&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>During the initial render, the following things would happen,</p><ol><li>A column with a button at center would render.</li><li>DisposableEffect would be called.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*scJdmo_Co8wtTMjfqT89MQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqRfrKDjIJ6TTMgT9MzkaQ.png" /></figure><p>When the button is clicked, the following things would happen</p><ol><li>It changes the value of count.</li><li><em>count</em> is a state, it will trigger the recomposition.</li><li>On recomposition, <em>DisposableEffect</em> leaves the composition and re-enters; hence <em>onDispose</em> will be called and the <strong>effect will be called again</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*H2XzGgsOj4Y4BhmoFqmnnw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzaLDgTlKCLhNJs0ex0N5A.png" /></figure><h3><strong>Conclusion</strong></h3><p>SideEffect is a very helpful concept in compose for complex resource management. It needs to be used wisely.</p><p>Generally it is recommended to not have side effects when there is lot of recompositions possible. (<em>DisposableEffect would be called on every re-composition</em>)</p><p><strong>References</strong> : <a href="https://developer.android.com/jetpack/compose/side-effects#disposableeffect">https://developer.android.com/jetpack/compose/side-effects#disposableeffect</a></p><p>Thanks for reading the article, Give applause if you really like it as it means a lot to me. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=739e83af347f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>