<?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 Ali Khavari Khorasani on Medium]]></title>
        <description><![CDATA[Stories by Ali Khavari Khorasani on Medium]]></description>
        <link>https://medium.com/@khorassani64?source=rss-7cc283c33fe1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7H5Jb7VxDPC0B9jA6XI24w.jpeg</url>
            <title>Stories by Ali Khavari Khorasani on Medium</title>
            <link>https://medium.com/@khorassani64?source=rss-7cc283c33fe1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:43:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khorassani64/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[Building Adaptive Android Layouts with Jetpack Compose]]></title>
            <link>https://medium.com/@khorassani64/building-adaptive-android-layouts-with-jetpack-compose-0e1cca3d5b22?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e1cca3d5b22</guid>
            <category><![CDATA[android-adaptive-compose]]></category>
            <category><![CDATA[compose-adaptive-layouts]]></category>
            <category><![CDATA[adaptive-ui-in-compose]]></category>
            <category><![CDATA[compose-window-layouts]]></category>
            <category><![CDATA[compose-responsive-ui]]></category>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Tue, 26 May 2026 19:47:27 GMT</pubDate>
            <atom:updated>2026-05-26T19:47:27.877Z</atom:updated>
            <content:encoded><![CDATA[<p>For many years, Android developers implemented different UI layouts for phones and tablets using resource qualifiers such as:</p><pre>layout-sw600dp</pre><p>This approach worked well and allowed Android to automatically load different XML layouts depending on the screen size.</p><p>With Jetpack Compose, Google now recommends a more adaptive approach. Instead of maintaining separate layout files for phones and tablets, we can dynamically adapt the UI based on the current window size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smFhR8gnEfA21nHvpfTuQw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/chau_cn-3768106/">chau_cn</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><p>This modern approach makes applications more flexible for:</p><ul><li>phones</li><li>tablets</li><li>foldables</li><li>split-screen mode</li><li>resizable windows</li></ul><p>In this article, we’ll create a simple adaptive layout using the latest recommended APIs from Google.</p><h4>Add the Adaptive Dependency</h4><p>First, add the Material 3 adaptive dependency:</p><pre>implementation(&quot;androidx.compose.material3.adaptive:adaptive:&lt;latest-version&gt;&quot;)</pre><h4>Get the Current Window Size</h4><p>Google’s latest documentation recommends using:</p><pre>val windowSizeClass =<br>    currentWindowAdaptiveInfo().windowSizeClass</pre><p>This API automatically reacts to window size changes such as:</p><ul><li>rotation</li><li>split-screen mode</li><li>foldable resizing</li><li>tablet multi-window mode</li></ul><p>Example:</p><pre>@Composable<br>fun MyApp() {<br><br>    val windowSizeClass =<br>        currentWindowAdaptiveInfo().windowSizeClass<br><br>    HomeScreen(windowSizeClass)<br>}</pre><h4>Understanding Window Size Classes</h4><p>Window size classes categorize available width and height.</p><p>The most important width categories are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G00sfmnVr3CNd5nP7wkvNg.png" /><figcaption><a href="https://developer.android.com/static/develop/ui/compose/images/layouts/adaptive/window-size-classes/window_size_classes_width.png"><em>Window size classes based on display width</em></a></figcaption></figure><p>Google recently also introduced support for Large and Extra Large breakpoints for desktop-style experiences.</p><p>In most cases, width is more important than height when designing adaptive layouts.</p><h4>Create Different Layouts</h4><p>We can now adapt the UI depending on the available width.</p><pre>@Composable<br>fun HomeScreen(<br>    windowSizeClass: WindowSizeClass<br>) {<br><br>    when (windowSizeClass.windowWidthSizeClass) {<br><br>        WindowWidthSizeClass.COMPACT -&gt; {<br>            PhoneLayout()<br>        }<br><br>        else -&gt; {<br>            TabletLayout()<br>        }<br>    }<br>}</pre><h4>Phone Layout Example</h4><p>For compact screens, a simple vertical list works well.</p><pre>@Composable<br>fun PhoneLayout() {<br><br>    LazyColumn(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp)<br>    ) {<br><br>        items(20) { index -&gt;<br><br>            Card(<br>                modifier = Modifier<br>                    .fillMaxWidth()<br>                    .padding(vertical = 8.dp)<br>            ) {<br><br>                Text(<br>                    text = &quot;Phone Item $index&quot;,<br>                    modifier = Modifier.padding(16.dp)<br>                )<br>            }<br>        }<br>    }<br>}</pre><h4>Tablet Layout Example</h4><p>On larger screens, we can improve the experience using a grid and side navigation.</p><pre>@Composable<br>fun TabletLayout() {<br><br>    Row(<br>        modifier = Modifier.fillMaxSize()<br>    ) {<br><br>        NavigationRail {<br><br>            NavigationRailItem(<br>                selected = true,<br>                onClick = {},<br>                icon = {<br>                    Icon(<br>                        imageVector = Icons.Default.Home,<br>                        contentDescription = null<br>                    )<br>                }<br>            )<br>        }<br><br>        LazyVerticalGrid(<br>            columns = GridCells.Fixed(2),<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(24.dp),<br>            horizontalArrangement = Arrangement.spacedBy(16.dp),<br>            verticalArrangement = Arrangement.spacedBy(16.dp)<br>        ) {<br><br>            items(20) { index -&gt;<br><br>                Card {<br><br>                    Text(<br>                        text = &quot;Tablet Item $index&quot;,<br>                        modifier = Modifier.padding(24.dp)<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>What About </strong><strong>sw600dp?</strong></p><p>Resource qualifiers like sw600dp are still useful for:</p><ul><li>dimensions</li><li>font sizes</li><li>resource values</li></ul><p>Example:</p><pre>values-sw600dp/</pre><p>However, for screen layouts, Jetpack Compose’s adaptive approach is usually cleaner and easier to maintain because the UI reacts directly to the available window size.</p><h4>Best Practices</h4><ul><li>Design based on available space instead of device type</li><li>Avoid hardcoded isTablet checks</li><li>Use grids and multi-pane layouts on larger screens</li><li>Test your UI with different window sizes</li><li>Avoid simply stretching phone layouts on tablets</li></ul><h3>Conclusion</h3><p>Jetpack Compose introduces a more modern way to build Android layouts compared to the traditional sw600dp approach.</p><p>By using currentWindowAdaptiveInfo() and WindowSizeClass, we can dynamically customize layouts for phones, tablets, foldables, and resizable windows while keeping a single, maintainable Compose codebase.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e1cca3d5b22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Git Merge, Rebase, and Cherry-pick]]></title>
            <link>https://medium.com/@khorassani64/understanding-git-merge-rebase-and-cherry-pick-84a2916f7b2f?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a2916f7b2f</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 18:01:51 GMT</pubDate>
            <atom:updated>2025-12-26T18:02:46.286Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with Git, one of the most important skills is understanding how to integrate changes from one branch into another. Whether you are collaborating with a team, maintaining a long-lived feature branch, or fixing a bug from another branch, Git provides multiple tools to help you manage history and code integration.</p><p>Three of the most commonly used (and often misunderstood) commands for this purpose are <strong>git merge</strong>, <strong>git rebase</strong>, and <strong>git cherry-pick</strong>. While they all move changes between branches, they do so in very different ways, with different impacts on project history.</p><p>In this article, we’ll briefly explain each command, show the basic Git commands, and discuss <strong>when you should and should not use them</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UszRNwXGM3AtIc18bgvjnQ.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/congerdesign-509903/">congerdesign</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>Git Merge</h3><p>git merge combines the history of two branches by creating a <strong>merge commit</strong>. This commit has two parents and represents the point where the branches come together. Git merge <strong>preserves the full history</strong> of both branches exactly as it happened.</p><h4>How to do it?</h4><p>To merge<strong> </strong><strong>main </strong>into your branch (let’s say your branch is feature-branch), the standard and safe sequence of Git commands is:</p><p>1️⃣ Make sure you have the latest main</p><pre>git fetch origin<br>git checkout main<br>git pull origin main</pre><p>2️⃣ Switch back to your branch</p><pre>git checkout feature-branch</pre><p>3️⃣ Merge main into your branch</p><pre>git merge main</pre><p>Let’s say your repository currently looks like this:</p><pre>A -- B -- C -- D  (main)<br>       \<br>        E -- F    (feature-branch)</pre><p>After merging, you <em>combine</em> histories:</p><pre>A -- B -- C -- D  (main)<br>       \         \<br>        E -- F ---- G   (feature-branch)</pre><p>After merge feature-branch back into main :</p><pre>A -- B -- C -- D  ----------- H   (main)<br>       \         \         /<br>        E -- F ---- G ----/</pre><p>🟢 G is a <strong>merge commit</strong> that brings in the new commits from main (C and D) into your branch.<br> ✅ History is fully preserved — no rewriting.</p><h4>When to use git merge</h4><ul><li>When working in <strong>shared branches</strong> (e.g., team feature branches).</li><li>When you want to <strong>preserve exact history.</strong></li><li>When following Git Flow or trunk-based development with merge commits.</li><li>When clarity of collaboration history is important.</li></ul><h4>When not to use git merge</h4><ul><li>When you want a <strong>clean, linear history</strong></li><li>When your branch has many small or experimental commits you’d prefer to clean up first.</li></ul><h3>Git Rebase</h3><p>git rebase moves (replays) commits from one branch on top of another branch. Instead of creating a merge commit, Git <strong>rewrites commit history</strong> by creating new commits.</p><h4>How to do it?</h4><p>In order to rebase feature-branch onto main :</p><p>1️⃣ Make sure you have the latest main</p><pre>git fetch origin<br>git checkout main<br>git pull origin main</pre><p>2️⃣ Switch back to your branch</p><pre>git checkout feature-branch</pre><p>3️⃣ Rebase feature-branch onto main</p><pre>git rebase main</pre><p>This reapplies the feature branch commits on top of the latest main branch. If your branch already exists on remote — rebasing rewrites history so we need force-push to apply it.</p><pre>git push --force</pre><p>Let’s say your repository currently looks like this:</p><pre>A -- B -- C -- D  (main)<br>       \<br>        E -- F    (feature-branch)</pre><p>After rebasing:</p><pre>A -- B -- C -- D  (main)<br>                  \<br>                   E&#39; -- F&#39;  (feature-branch)</pre><p>After merge (or fast-forward) feature-branch back into main :</p><pre>A -- B -- C -- D -- E&#39; -- F&#39;   (main, feature-branch)</pre><p>🟢 E&#39; and F&#39; are <strong>new commits</strong> (copies of your original E and F) but now based on top of D.<br> ❗ This rewrites commit history — useful for clean, linear history before merging.</p><h4>When to use git rebase</h4><ul><li>Before merging a feature branch into main</li><li>On <strong>local or private branches</strong></li><li>To keep commit history clean and readable</li><li>When you want to avoid unnecessary merge commits</li></ul><h4>When not to use git rebase</h4><ul><li>On <strong>shared branches</strong> that others are using</li><li>On branches that have already been pushed and pulled by others</li></ul><blockquote><em>⚠️ Rewriting history on shared branches can cause serious conflicts for teammates.</em></blockquote><h3>Git Cherry-pick</h3><p>git cherry-pick applies <strong>specific commits</strong> from one branch onto another branch. Instead of merging all changes, you select exactly which commit you want.</p><h4>How to do it?</h4><pre>git checkout main<br>git cherry-pick &lt;commit-hash&gt;</pre><p>This applies the selected commit to main.</p><p>Let’s say your repository currently looks like this:</p><pre>A -- B -- C -- D  (main)<br>       \<br>        E -- F -- G  (feature-branch)</pre><p>Let’s say:</p><ul><li>F = bug fix you want</li><li>G = experimental change you <strong>don’t</strong> want</li></ul><p>And we want to cherry-pick commit F into main :</p><p>After cherry-pick:</p><pre>A -- B -- C -- D -- F&#39;   (main)<br>       \<br>        E -- F -- G     (feature-branch)</pre><p>🟢 F&#39; is a <strong>new commit</strong></p><ul><li>Same code changes as F</li><li><strong>Different commit hash</strong></li><li>Original F still exists on feature-branch</li></ul><h4>🧩 Multiple cherry-picks</h4><p>You can cherry-pick more than one commit:</p><pre>git cherry-pick F G</pre><p>Result:</p><pre>A -- B -- C -- D -- F&#39; -- G&#39;   (main)<br>       \<br>        E -- F -- G           (feature-branch)</pre><h4>When to use git cherry-pick</h4><ul><li>Applying a <strong>hotfix</strong> from one branch to another</li><li>Selecting a single bug fix without merging the entire branch</li><li>Backporting fixes to release branches</li></ul><h4>When not to use git cherry-pick</h4><ul><li>When you need the <strong>full context</strong> of a branch</li><li>When cherry-picking many commits (can make history confusing)</li><li>As a replacement for proper branching strategy</li></ul><h4><strong>Summary</strong></h4><p>Understanding when and how to use these commands is crucial for maintaining a clean project history, collaborating effectively with team members, and managing complex development workflows.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked it please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a2916f7b2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semaphores in Kotlin Coroutines]]></title>
            <link>https://medium.com/@khorassani64/semaphores-in-kotlin-coroutines-ddb8cde92d8a?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb8cde92d8a</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 04:17:48 GMT</pubDate>
            <atom:updated>2025-03-16T04:21:14.119Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with concurrent operations in Kotlin Coroutines, managing access to shared resources is crucial. If multiple coroutines try to access a shared resource simultaneously, it can lead to <strong>race conditions</strong>, <strong>data corruption</strong>, or <strong>unexpected behavior</strong>.</p><p>One of the best mechanisms to control concurrency in Kotlin Coroutines is the <strong>Semaphore</strong>. In this article, we will explore what a <strong>Semaphore</strong> is, why it’s useful in Android, and how to implement it in a Jetpack Compose application using Hilt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyR238uBy4hWCz16P5DFSw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/thedigitalartist-202249/">TheDigitalArtist</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>What is a Semaphore?</h3><p>A <strong>Semaphore</strong> is a concurrency control mechanism that restricts the number of coroutines accessing a shared resource at the same time. It works by maintaining a <strong>permit count</strong>, which determines how many coroutines can execute a given operation concurrently.</p><p>We can use Semaphores in:</p><ul><li><strong>Limiting API calls</strong> to prevent exceeding rate limits.</li><li><strong>Controlling database writes</strong> to avoid deadlocks.</li><li><strong>Managing access to a shared file</strong> in multi-threaded environments.</li></ul><h3>Implementing Semaphore in an Android App</h3><p>Let’s implement a simple Android application that fetches data from a simulated network request using <strong>Semaphore</strong> to control concurrency.</p><h4>Step 1: Add Dependencies</h4><pre>dependencies {<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1&quot;)<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.1&quot;)<br><br>    implementation(&quot;com.google.dagger:hilt-android:2.51.1&quot;)<br>    kapt(&quot;com.google.dagger:hilt-compiler:2.51.1&quot;)<br>}</pre><h4>Step 2: Enable Hilt in Your Application</h4><p>In our Application class, we have to annotate it with @HiltAndroidApp:</p><pre>@HiltAndroidApp<br>class SemaphoreApp : Application()</pre><h4>Step 3: Create a Hilt Module for Semaphore</h4><p>We define a Hilt module that provides the <strong>concurrency limit</strong> and the <strong>Semaphore instance</strong>.</p><pre>@Module<br>@InstallIn(ViewModelComponent::class) // Scoped to ViewModel<br>object SemaphoreModule {<br><br>    @Provides<br>    fun provideConcurrentLimit(): Int = 2// Configurable concurrency limit<br><br>    @Provides<br>    fun provideSemaphore(concurrentLimit: Int): Semaphore = Semaphore(concurrentLimit)<br>}</pre><p>The Semaphore is initialized with concurrentLimit = 2, which means <strong>only two coroutines can run concurrently</strong>, while others will be <strong>suspended</strong> until a permit is released.</p><h4>Step 4: Implement ViewModel Using Semaphore</h4><pre>@HiltViewModel<br>class SemaphoreViewModel @Inject constructor(<br>    private val semaphore: Semaphore<br>) : ViewModel() {<br><br>    private val _dataFlow = MutableStateFlow&lt;List&lt;String&gt;&gt;(emptyList())<br>    val dataFlow = _dataFlow.asStateFlow()<br><br>    fun fetchData() {<br>        val responses = mutableListOf&lt;String&gt;()<br><br>        repeat(5) { index -&gt;<br>            viewModelScope.launch(Dispatchers.IO) {<br>                semaphore.withPermit {<br>                    try {<br>                        val result = async { simulateNetworkRequest(index) }<br>                        responses.add(result.await())<br>                        _dataFlow.value = responses.toList() // Update UI<br>                    } catch (e: Exception) {<br>                        Log.e(&quot;SemaphoreViewModel&quot;, &quot;Error fetching data: ${e.message}&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    private suspend fun simulateNetworkRequest(index: Int): String {<br>        Log.d(&quot;SemaphoreViewModel&quot;, &quot;Fetching data for request $index...&quot;)<br>        kotlinx.coroutines.delay(2000) // Simulate network delay<br>        return &quot;Data from request $index&quot;<br>    }<br>}</pre><h4>Step 5: Create a Jetpack Compose UI to Use the ViewModel</h4><p>Now, we build a simple Jetpack Compose screen to trigger data fetching.</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            SemaphoreScreen()<br>        }<br>    }<br>}<br><br>@Composable<br>fun SemaphoreScreen(viewModel: SemaphoreViewModel = viewModel()) {<br>    val data by viewModel.dataFlow.collectAsState()<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Button(onClick = { viewModel.fetchData() }) {<br>            Text(&quot;Fetch Data&quot;)<br>        }<br><br>        Spacer(modifier = Modifier.height(16.dp))<br><br>        LazyColumn {<br>            items(data) { item -&gt;<br>                Text(item, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(8.dp))<br>            }<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>Using a <strong>Semaphore in Kotlin Coroutines</strong> is a powerful way to <strong>control concurrency</strong> in Android applications. It ensures that resource-intensive tasks like <strong>network requests or database operations</strong> don’t overload the system. By leveraging <strong>Hilt</strong>, we avoid hardcoding values and keep the code modular and reusable.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb8cde92d8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Android Keystore in Kotlin and Jetpack Compose]]></title>
            <link>https://medium.com/@khorassani64/using-android-keystore-in-kotlin-and-jetpack-compose-b85b3a922cf3?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b85b3a922cf3</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 05:31:13 GMT</pubDate>
            <atom:updated>2024-12-06T05:31:13.009Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital age, securing user data is a top priority for mobile applications. As Android developers, we often deal with sensitive information like passwords, API tokens, or personal user data. This data must be protected against unauthorized access and tampering.</p><p>The Android Keystore System is a powerful tool that provides secure key storage and management, ensuring cryptographic keys remain inaccessible even if a device is compromised. In this article, we will explore how the Keystore System strengthens app security and demonstrate its use in a Kotlin and Jetpack Compose application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xegd9XiC0TVwGuC1btchEw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/pexels-2286921/">Pexels</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>Using Android Keystore in Kotlin and Jetpack Compose</h3><h4>1. Setup</h4><p>Add the following dependency for cryptographic operations:</p><pre>implementation(&quot;androidx.security:security-crypto:1.1.0-alpha06&quot;)</pre><h4>2. Generating a Key</h4><p>Use the KeyGenerator to create a key in the Android Keystore:</p><pre>fun generateKey(alias: String) {<br>    val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, &quot;AndroidKeyStore&quot;)<br>    val keyGenParameterSpec = KeyGenParameterSpec.Builder(<br>        alias,<br>        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT<br>    )<br>        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)<br>        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)<br>        .setUserAuthenticationRequired(false) // Require user authentication if needed<br>        .build()<br><br>    keyGenerator.init(keyGenParameterSpec)<br>    keyGenerator.generateKey()<br>}</pre><h4>3. Encrypting Data</h4><p>Use the key stored in the Keystore for encryption:</p><pre>fun encryptData(alias: String, plaintext: ByteArray): Pair&lt;ByteArray, ByteArray&gt; {<br>    val keyStore = KeyStore.getInstance(&quot;AndroidKeyStore&quot;)<br>    keyStore.load(null)<br>    val secretKey = keyStore.getKey(alias, null) as SecretKey<br><br>    val cipher = Cipher.getInstance(&quot;AES/GCM/NoPadding&quot;)<br>    cipher.init(Cipher.ENCRYPT_MODE, secretKey)<br>    val iv = cipher.iv<br>    val ciphertext = cipher.doFinal(plaintext)<br>    return Pair(ciphertext, iv)<br>}</pre><h4>4. Decrypting Data</h4><p>Decrypt data using the same key:</p><pre>fun decryptData(alias: String, ciphertext: ByteArray, iv: ByteArray): ByteArray {<br>    val keyStore = KeyStore.getInstance(&quot;AndroidKeyStore&quot;)<br>    keyStore.load(null)<br>    val secretKey = keyStore.getKey(alias, null) as SecretKey<br><br>    val cipher = Cipher.getInstance(&quot;AES/GCM/NoPadding&quot;)<br>    val spec = GCMParameterSpec(128, iv)<br>    cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)<br>    return cipher.doFinal(ciphertext)<br>}</pre><h4>5. Integrating with Jetpack Compose</h4><p>In a Compose-based application, you can display data secured with Keystore. For example:</p><pre>@Composable<br>fun SecureDataScreen() {<br>    val alias = &quot;MyKeyAlias&quot;<br>    val plaintext = &quot;Secure message&quot;.toByteArray()<br><br>    var encryptedData by remember { mutableStateOf&lt;ByteArray?&gt;(null) }<br>    var decryptedText by remember { mutableStateOf&lt;String?&gt;(null) }<br><br>    Column {<br>        Button(onClick = {<br>            generateKey(alias)<br>            val (ciphertext, iv) = encryptData(alias, plaintext)<br>            encryptedData = ciphertext<br>            decryptedText = String(decryptData(alias, ciphertext, iv))<br>        }) {<br>            Text(&quot;Encrypt &amp; Decrypt&quot;)<br>        }<br><br>        encryptedData?.let {<br>            Text(&quot;Encrypted: ${it.joinToString()}&quot;)<br>        }<br><br>        decryptedText?.let {<br>            Text(&quot;Decrypted: $it&quot;)<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>The Android Keystore System is a cornerstone of app security, offering a secure way to manage and use cryptographic keys. By integrating it with Kotlin and Jetpack Compose, you can create secure, user-friendly apps that protect sensitive data.</p><p>In this example, I demonstrated how to use the Keystore for encrypting and decrypting data in a Compose application. With this approach, you can ensure your users’ data is safe from potential attacks, building trust and compliance in an ever-evolving digital landscape.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b85b3a922cf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering State Management in Android: Exploring rememberSaveable, mutableStateOf, LiveData, and…]]></title>
            <link>https://medium.com/@khorassani64/mastering-state-management-in-android-exploring-remembersaveable-mutablestateof-livedata-and-b76d585d9fed?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b76d585d9fed</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 04:17:07 GMT</pubDate>
            <atom:updated>2024-10-29T04:17:07.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering State Management in Android: Exploring rememberSaveable, mutableStateOf, LiveData, and StateFlow</h3><h3>Introduction</h3><p>State management is a critical aspect of Android development, particularly with the introduction of Jetpack Compose and its declarative UI approach. Managing state effectively ensures that applications respond dynamically to user actions, configuration changes, and asynchronous data updates. Android offers a variety of state management tools, each with unique characteristics and suitable use cases, allowing developers to create robust, adaptable, and high-performing applications.</p><p>In this article, we’ll dive into four powerful methods of state management in Android — rememberSaveable, mutableStateOf, LiveData, and StateFlow. We’ll explore how each tool functions, when to use them, and provide code examples to highlight their differences. By the end, you’ll have a clear understanding of how to integrate these tools to manage UI state and data flow effectively in your applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLH3GCdmDipMXtRYm5SEDQ.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/pexels-2286921/">Pexels</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>1. Using rememberSaveable</h3><p>rememberSaveable is used to remember a value across configuration changes (like screen rotations) in Jetpack Compose.</p><pre>@Composable<br>fun CounterScreen() {<br>    val count = rememberSaveable { mutableStateOf(0) }<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(text = &quot;Count: ${count.value}&quot;)<br>        Button(onClick = { count.value++ }) {<br>            Text(&quot;Increment&quot;)<br>        }<br>    }<br>}</pre><p>The count state will persist through configuration changes like screen rotation due to rememberSaveable. If you used remember instead, the state would reset on rotation.</p><h3>2. Using mutableStateOf</h3><p>mutableStateOf creates a mutable state object in a ViewModel or Composable. This state is not preserved across configuration changes unless used with rememberSaveable in Composables.</p><pre>@Composable<br>fun SimpleToggleScreen() {<br>    val isOn = remember { mutableStateOf(false) }<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(text = if (isOn.value) &quot;On&quot; else &quot;Off&quot;)<br>        Button(onClick = { isOn.value = !isOn.value }) {<br>            Text(&quot;Toggle&quot;)<br>        }<br>    }<br>}</pre><p>Here, isOn is a mutable state that allows toggling between &quot;On&quot; and &quot;Off&quot; each time the button is pressed. This state is local to the Composable and will not persist across configuration changes.</p><h3>3. Using LiveData in a ViewModel</h3><p>LiveData is lifecycle-aware, so it’s ideal for observing data in a Composable that updates automatically based on lifecycle changes.</p><pre>// ViewModel<br>class CounterViewModel : ViewModel() {<br>    private val _count = MutableLiveData(0)<br>    val count: LiveData&lt;Int&gt; get() = _count<br><br>    fun increment() {<br>        _count.value = (_count.value ?: 0) + 1<br>    }<br>}<br><br>// Composable<br>@Composable<br>fun CounterLiveDataScreen(viewModel: CounterViewModel = viewModel()) {<br>    val count by viewModel.count.observeAsState(0)<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(text = &quot;Count: $count&quot;)<br>        Button(onClick = { viewModel.increment() }) {<br>            Text(&quot;Increment&quot;)<br>        }<br>    }<br>}</pre><p>Here, count in CounterViewModel is exposed as LiveData. Inside the Composable, we observe this LiveData using observeAsState, which updates the Composable whenever count changes.</p><h3>4. Using StateFlow in a ViewModel</h3><p>StateFlow is used in combination with Kotlin Coroutines and is often favored over LiveData in modern Android development for reactive streams of data. Unlike LiveData, it is not lifecycle-aware but provides similar state management in a ViewModel.</p><pre>// ViewModel<br>class ToggleViewModel : ViewModel() {<br>    private val _isOn = MutableStateFlow(false)<br>    val isOn: StateFlow&lt;Boolean&gt; get() = _isOn<br><br>    fun toggle() {<br>        _isOn.value = !_isOn.value<br>    }<br>}<br><br>// Composable<br>@Composable<br>fun ToggleStateFlowScreen(viewModel: ToggleViewModel = viewModel()) {<br>    val isOn by viewModel.isOn.collectAsState()<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(text = if (isOn) &quot;On&quot; else &quot;Off&quot;)<br>        Button(onClick = { viewModel.toggle() }) {<br>            Text(&quot;Toggle&quot;)<br>        }<br>    }<br>}</pre><p>The isOn StateFlow in the ViewModel emits the current state, and collectAsState is used in the Composable to observe this flow and recompose the UI whenever isOn changes. This setup is great for asynchronous updates and background operations.</p><h3>Summary of When to Use Each</h3><ul><li><strong>rememberSaveable</strong>: Use when you need UI state in a Composable that survives configuration changes.</li><li><strong>mutableStateOf</strong>: Use for local Composable state, especially when persistence across configuration changes isn’t required.</li><li><strong>LiveData</strong>: Use in ViewModel for lifecycle-aware UI state, particularly when used in combination with older codebases.</li><li><strong>StateFlow</strong>: Use in ViewModel for reactive state management, particularly for modern, coroutine-based asynchronous flows and data streams.</li></ul><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b76d585d9fed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Delegation in Kotlin: A Guide to Cleaner Code]]></title>
            <link>https://medium.com/@khorassani64/mastering-delegation-in-kotlin-a-guide-to-cleaner-code-8ee53ad1c4c5?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ee53ad1c4c5</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 15:44:22 GMT</pubDate>
            <atom:updated>2024-09-27T15:44:22.170Z</atom:updated>
            <content:encoded><![CDATA[<p>In software development, writing clean, reusable, and maintainable code is a core principle for building robust applications. One design pattern that helps achieve this is delegation, where one object delegates responsibility for a task to another helper object. Kotlin, being a modern and versatile programming language, offers built-in support for delegation, making it even easier to implement this pattern in your projects. In this article, we’ll explore what delegation is, the benefits it offers, and how to apply it effectively with a real-world example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXmMM46aVWWapjB_al9Onw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/alexas_fotos-686414/">Alexas_Fotos</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>What is Delegation?</h3><p>Delegation is a design pattern that allows an object to pass on a task to another helper object. This means instead of handling everything itself, the delegating object relies on another object to provide the necessary functionality. It’s kind of like saying, “I trust you to handle this task.” In Kotlin, there’s a special keyword by that makes this process super smooth.</p><p>Kotlin provides two main types of delegation:</p><ol><li><strong>Property Delegation</strong>: Used when you want another object to handle the logic for getting and setting a property.</li><li><strong>Class Delegation</strong>: Used when a class wants to delegate certain functionalities to another object that implements an interface.</li></ol><p>Let’s focus on <strong>Property Delegation</strong>, as it’s the most commonly used, especially in Android development.</p><h3>1. Property Delegation</h3><p>When you declare a property with by in Kotlin, you are delegating its getter and setter to a delegate object. This is very useful for cases like lazy initialization, observable properties, or custom property behaviors.</p><p><strong>Syntax:</strong></p><pre>val propertyName: Type by delegate</pre><h3>Common Property Delegates in Kotlin</h3><p>1- <strong>lazy</strong>: Initializes the property only when it is accessed for the first time.</p><pre>val lazyValue: String by lazy {<br>    println(&quot;Computed!&quot;)<br>    &quot;Hello, World!&quot;<br>}</pre><ul><li>When lazyValue is accessed for the first time, the code inside lazy { ... } is executed, and &quot;Computed!&quot; is printed.</li><li>The result (“Hello, World!”) is stored, and on subsequent accesses, the stored value is returned without re-executing the block.</li></ul><p>2- <strong>observable</strong>: Allows you to track changes to a property.</p><pre>var name: String by Delegates.observable(&quot;Initial Value&quot;) { property, oldValue, newValue -&gt;<br>    println(&quot;$oldValue -&gt; $newValue&quot;)<br>}</pre><p>. Whenever name is changed, the lambda is called.</p><p>3- <strong>preferenceDataStore</strong>: This is an Android-specific delegate provided by the Jetpack DataStore library to create a DataStore instance.</p><pre>private val Context.dataStore by preferencesDataStore(name = &quot;user_prefs&quot;)</pre><p>. preferencesDataStore delegate to handle the creation and retrieval of the DataStore instance for storing preferences.</p><p>4- Delegation in Jetpack Compose:</p><pre>var state: Int by remember { mutableStateOf(1) }</pre><ul><li>mutableStateOf(1) creates a MutableState&lt;Int&gt; object that can read and write the state value (Int in this case).</li><li>By using by, you don’t directly access the MutableState object but instead treat state as a normal variable of type Int. Internally, any read or write operation on state is managed by the MutableState instance created by mutableStateOf .</li></ul><h3>2. Class Delegation</h3><p>Class delegation is used when you want a class to implement an interface but delegate the implementation of its methods to another object.</p><pre>interface Printer {<br>    fun printMessage()<br>}<br><br>class RealPrinter : Printer {<br>    override fun printMessage() {<br>        println(&quot;Printing message&quot;)<br>    }<br>}<br><br>class DelegatingPrinter(printer: Printer) : Printer by printer<br><br>fun main() {<br>    val printer = RealPrinter()<br>    val delegatingPrinter = DelegatingPrinter(printer)<br>    delegatingPrinter.printMessage()  // Output: Printing message<br>}</pre><h3>Why Use Delegation?</h3><ul><li><strong>Code Reusability</strong>: Delegates allow you to reuse logic, reducing redundancy.</li><li><strong>Encapsulation</strong>: Delegation lets you encapsulate behavior, which keeps your code clean and maintainable.</li><li><strong>Flexibility</strong>: You can change the delegate’s behavior without modifying the original code.</li></ul><h3>Conclusion</h3><p>Kotlin’s delegation feature is honestly one of my favorite things about the language. It allows me to write more maintainable, reusable, and flexible code, and it helps keep my classes clean and focused. Instead of reinventing the wheel, I can delegate tasks to objects that are designed to handle them.</p><p>If you haven’t used delegation in your Kotlin projects yet, I highly recommend giving it a try. You’ll find that it not only makes your code cleaner but also much easier to manage as your projects grow.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ee53ad1c4c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Stripe Payment Gateways in Android Using Kotlin & Jetpack Compose]]></title>
            <link>https://medium.com/@khorassani64/implementing-stripe-payment-gateways-in-android-using-kotlin-jetpack-compose-5f91df2b6130?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f91df2b6130</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 19:04:50 GMT</pubDate>
            <atom:updated>2024-09-09T15:46:05.001Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapidly evolving world of mobile commerce, integrating secure and efficient payment solutions is essential for any Android application. Stripe, a leading payment gateway, provides a robust platform for handling online transactions with ease. With Kotlin’s expressive syntax and Jetpack Compose’s modern UI toolkit, developers can create seamless payment experiences that are both user-friendly and secure.</p><p>In this article, we’ll explore how to integrate Stripe into an Android application using Kotlin and Jetpack Compose. We’ll cover the necessary steps to set up Stripe, handle payment processes, and ensure a smooth user experience — all while leveraging the power of Kotlin and the flexibility of Compose. Whether you’re building an e-commerce app or adding a payment feature to your existing project, this guide will help you get started with Stripe in no time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKRAKZhdKIQ0yZW4wBydFw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/michaelwuensch-4163668/">MichaelWuensch</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>Prerequisites</h3><p>Before diving into the implementation, ensure you have the following:</p><ol><li><strong>Basic knowledge of Kotlin and Jetpack Compose</strong>: This article assumes familiarity with Kotlin syntax and Compose UI elements.</li><li><strong>A Stripe account</strong>: Sign up for a Stripe account and obtain your API keys.</li><li><strong>Android Studio setup</strong>: Ensure you have Android Studio installed with the latest stable version.</li></ol><h4><strong>Step 1: Set Up Dependencies</strong></h4><p>Add the necessary dependencies for Stripe in your build.gradle file:</p><pre>dependencies {<br>    implementation &#39;com.stripe:stripe-android:20.48.6&#39;<br>    ...<br>}</pre><h4>Step 2: Store Stripe Keys in Local Properties</h4><ul><li>Open the local.properties file (create it if it doesn’t exist).</li><li>Add your Stripe keys as follows:</li></ul><pre>stripe.publishable.key=&quot;your_publishable_key&quot;<br>stripe.secret.key=&quot;your_secret_key&quot;</pre><h4>Step 3: Implementing Stripe Payment in Jetpack Compose</h4><p><strong>Composable for Payment</strong>: Create a composable function to handle the payment UI.</p><pre>@Composable<br>fun PaymentScreen(<br>    viewModel: PaymentViewModel,<br>    paymentSheet: PaymentSheet<br>) {<br>    val context = LocalContext.current<br>    val paymentState by viewModel.paymentState.collectAsState()<br><br><br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        when (paymentState) {<br>            is PaymentState.Loading -&gt; CircularProgressIndicator()<br>            is PaymentState.Success -&gt; Text(&quot;Payment Successful!&quot;)<br>            is PaymentState.Error -&gt; {<br>                Text(&quot;Payment Failed: ${(paymentState as PaymentState.Error).message}&quot;)<br>            }<br><br>            is PaymentState.Ready -&gt; {<br>                Button(onClick = {<br>                    viewModel.startPayment()<br>                }) {<br>                    Text(&quot;Pay Now&quot;)<br>                }<br>            }<br><br>            is PaymentState.ClientSecretReceived -&gt; {<br>                LaunchedEffect(paymentState) {<br>                    (paymentState as PaymentState.ClientSecretReceived).clientSecret?.let { clientSecret -&gt;<br>                        paymentSheet.presentWithPaymentIntent(<br>                            paymentIntentClientSecret = clientSecret,<br>                            configuration = PaymentSheet.Configuration(<br>                                merchantDisplayName = &quot;Example, Inc.&quot;,<br>                                allowsDelayedPaymentMethods = true<br>                            )<br>                        )<br>                        (paymentState as PaymentState.ClientSecretReceived).publishableKey?.let { publishableKey -&gt;<br>                            PaymentConfiguration.init(context, publishableKey)<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Step 4: Handling Payment in the ViewModel</h4><p>Now, let’s handle the payment process. You’ll need to send payment details to your backend server, which will communicate with Stripe’s API. For simplicity, we’ll focus on the front-end integration here.</p><p>Create a ViewModel to manage the payment process:</p><pre>class PaymentViewModel : ViewModel() {<br>    private val _paymentState = MutableStateFlow&lt;PaymentState&gt;(PaymentState.Ready)<br>    val paymentState: StateFlow&lt;PaymentState&gt; = _paymentState<br><br>    fun startPayment() {<br>        viewModelScope.launch {<br>            _paymentState.value = PaymentState.Loading<br>            try {<br>                val response = createPaymentIntent() // Implement your network call to backend here<br>                val clientSecret = response.clientSecret<br>                _paymentState.value = PaymentState.ClientSecretReceived(clientSecret)<br>            } catch (e: Exception) {<br>                _paymentState.value = PaymentState.Error(e.message ?: &quot;Unknown error&quot;)<br>            }<br>        }<br>    }<br><br>    private suspend fun createPaymentIntent(): PaymentIntentResponse {<br>        // Implement network call to your backend to create a payment intent<br>    }<br><br>    fun onPaymentSuccess() {<br>        _paymentState.value = PaymentState.Success<br>    }<br><br>    fun onPaymentCancelled() {<br>        _paymentState.value = PaymentState.Ready<br>    }<br><br>    fun onPaymentFailed(errorMessage: String?) {<br>        _paymentState.value = PaymentState.Error(errorMessage ?: &quot;Unknown error&quot;)<br>    }<br>}<br><br>sealed class PaymentState {<br>    data object Ready : PaymentState()<br>    data object Loading : PaymentState()<br>    data object Success : PaymentState()<br>    class Error(val message: String) : PaymentState()<br>    class ClientSecretReceived(<br>        val clientSecret: String?,<br>        val publishableKey: String?<br>    ) : PaymentState()<br>}</pre><h4>Step 5: Integrating Stripe Payment Sheet in MainActivity</h4><p>In this section, we initialize the Stripe Payment Sheet in the MainActivity and handle the different outcomes of the payment process. By using the PaymentSheet class from the Stripe SDK, we can present a user-friendly payment interface with minimal code. The result of the payment process is handled through the onPaymentResult callback, which triggers the appropriate response in the PaymentViewModel.</p><pre>class MainActivity : ComponentActivity() {<br><br>    private val viewModel: PaymentViewModel by viewModels()<br>    private lateinit var paymentSheet: PaymentSheet<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        paymentSheet = PaymentSheet(this, ::onPaymentResult)<br><br>        setContent {<br>            StripePaymentTheme {<br>                PaymentScreen(viewModel, paymentSheet)<br>            }<br>        }<br>    }<br><br>    private fun onPaymentResult(paymentSheetResult: PaymentSheetResult) {<br>        when (paymentSheetResult) {<br>            is PaymentSheetResult.Completed -&gt; {<br>                // Handle successful payment<br>                viewModel.onPaymentSuccess()<br>            }<br>            is PaymentSheetResult.Canceled -&gt; {<br>                // Handle payment cancellation<br>                viewModel.onPaymentCancelled()<br>            }<br>            is PaymentSheetResult.Failed -&gt; {<br>                // Handle payment failure<br>                viewModel.onPaymentFailed(paymentSheetResult.error.message)<br>            }<br>        }<br>    }<br>}</pre><h4>Step 6: Create a server to handle paymentIntent</h4><p>Here is an example of a php server which returns the client_secret of the created payment intent.</p><pre>&lt;?php<br>require &#39;vendor/autoload.php&#39;;<br>$stripe = new \Stripe\StripeClient(&#39;your_secret_key&#39;);<br>$customer = $stripe-&gt;customers-&gt;create();<br>$ephemeralKey = $stripe-&gt;ephemeralKeys-&gt;create([<br>  &#39;customer&#39; =&gt; $customer-&gt;id,<br>], [<br>  &#39;stripe_version&#39; =&gt; &#39;2024-06-20&#39;,<br>]);<br>$paymentIntent = $stripe-&gt;paymentIntents-&gt;create([<br>  &#39;amount&#39; =&gt; 1099,<br>  &#39;currency&#39; =&gt; &#39;eur&#39;,<br>  &#39;customer&#39; =&gt; $customer-&gt;id,<br>  &#39;automatic_payment_methods&#39; =&gt; [<br>    &#39;enabled&#39; =&gt; &#39;true&#39;,<br>  ],<br>]);<br>header(&#39;Content-Type: application/json&#39;);<br>echo json_encode(<br>  array(<br>    &#39;paymentIntent&#39; =&gt; $paymentIntent-&gt;client_secret,<br>    &#39;ephemeralKey&#39; =&gt; $ephemeralKey-&gt;secret,<br>    &#39;customer&#39; =&gt; $customer-&gt;id,<br>    &#39;publishableKey&#39; =&gt; &#39;your_publishable_key&#39;<br>  )<br>);<br>http_response_code(200);<br>?&gt;</pre><h3>Conclusion</h3><p>Integrating Stripe into your Android application using Kotlin and Jetpack Compose provides a modern and efficient way to handle payments, enhancing both the security and user experience of your app. By leveraging the Stripe Payment Sheet, you can simplify the payment process while maintaining full control over the payment flow and outcomes. Kotlin’s concise syntax and Jetpack Compose’s declarative UI framework make it easy to create a responsive and user-friendly payment interface.</p><h4>Reference:</h4><p><a href="https://docs.stripe.com/payments/accept-a-payment?platform=android">Accept a payment</a></p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f91df2b6130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Media3 (ExoPlayer) with Kotlin Jetpack Compose]]></title>
            <link>https://medium.com/@khorassani64/using-media3-with-kotlin-jetpack-compose-f1c033acd016?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c033acd016</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 05:24:46 GMT</pubDate>
            <atom:updated>2024-09-13T15:37:23.107Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Media3</strong> is a suite of libraries developed by Google for handling media playback and related functionalities in Android applications. It is designed to replace the previous ExoPlayer library and provides a more streamlined and integrated approach to media playback, including audio and video streaming. Media3 includes features such as:</p><ul><li><strong>Media playback</strong>: Support for various media formats and adaptive streaming.</li><li><strong>Media controls</strong>: Handling of media controls like play, pause, seek, etc.</li><li><strong>Media sessions</strong>: Integration with Android’s media session framework for better media control and notification.</li><li><strong>UI components</strong>: Pre-built UI components for media controls and playback.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVdnYOXcDmYtDunRf9kLvg.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/javierdumont-14443229/">javierdumont</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><p>To use Media3 in a Jetpack Compose application, you have to follow these steps:</p><p><strong>1- Add dependencies</strong>: To use Media3 in your Android project, add the necessary dependencies to your build.gradle (Module: app) file:</p><pre>implementation(&quot;androidx.media3:media3-exoplayer:1.3.1&quot;)<br>implementation(&quot;androidx.media3:media3-ui:1.3.1&quot;)<br>implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.8.3&quot;)</pre><p><strong>2- Create a PlayerViewModel for managing video player instance:</strong></p><p>Here we define a PlayerViewModel to create and manage our ExoPlayer instance and add it’s properties, in PlayerViewModel we can define a playerState to keep the current state of the player, by saving the currentPosition of video of the player in savePlayerState function, video will continue after screen rotation or any other configuration changes.</p><p>we defineHandleError function in order to handle different PlaybackExceptions and call this function in onPlayerError .</p><pre>class PlayerViewModel : ViewModel() {<br><br>    private val _playerState = MutableStateFlow&lt;ExoPlayer?&gt;(null)<br>    val playerState: StateFlow&lt;ExoPlayer?&gt; = _playerState<br><br>    private var currentPosition: Long = 0L<br><br>    fun initializePlayer(context: Context, videoUrl: String) {<br>        if (_playerState.value == null) {<br>            viewModelScope.launch {<br>                val exoPlayer = ExoPlayer.Builder(context).build().also {<br>                    val mediaItem = MediaItem.fromUri(Uri.parse(videoUrl))<br>                    it.setMediaItem(mediaItem)<br>                    it.prepare()<br>                    it.playWhenReady = true<br>                    it.seekTo(currentPosition)<br>                    it.addListener(object : Player.Listener {<br>                        override fun onPlayerError(error: PlaybackException) {<br>                            handleError(error)<br>                        }<br>                    })<br>                }<br>                _playerState.value = exoPlayer<br>            }<br>        }<br>    }<br><br>    fun savePlayerState() {<br>        _playerState.value?.let {<br>            currentPosition = it.currentPosition<br>        }<br>    }<br><br>    fun releasePlayer() {<br>        _playerState.value?.release()<br>        _playerState.value = null<br>    }<br><br>    private fun handleError(error: PlaybackException) {<br>        when (error.errorCode) {<br>            PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED -&gt; {<br>                // Handle network connection error<br>                println(&quot;Network connection error&quot;)<br>            }<br><br>            PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND -&gt; {<br>                // Handle file not found error<br>                println(&quot;File not found&quot;)<br>            }<br><br>            PlaybackException.ERROR_CODE_DECODER_INIT_FAILED -&gt; {<br>                // Handle decoder initialization error<br>                println(&quot;Decoder initialization error&quot;)<br>            }<br><br>            else -&gt; {<br>                // Handle other types of errors<br>                println(&quot;Other error: ${error.message}&quot;)<br>            }<br>        }<br>    }<br>}</pre><p><strong>3- Create a Composable function for the video player</strong>:</p><p>Here we use ExoPlayer and AndroidView to integrate with Jetpack Compose. By calling initializePlayer function of our viewModel in a LaunchEffect we initialize our ExoPlayer instance. Using DisposableEffect allows us to perform cleanup actions when the composable leaves the composition. In onDispose first we save playerState and then release the player.</p><p>In Media3AndroidView composable we define our AndroidView, we embed the PlayerView into the Compose UI by using AndroidView.</p><pre>@Composable<br>fun Media3PlayerView(videoUrl: String, playerViewModel: PlayerViewModel = viewModel()) {<br><br>    val context = LocalContext.current<br>    val player by playerViewModel.playerState.collectAsState()<br><br>    LaunchedEffect(videoUrl) {<br>        playerViewModel.initializePlayer(context, videoUrl)<br>    }<br><br>    DisposableEffect(Unit) {<br>        onDispose {<br>            playerViewModel.savePlayerState()<br>            playerViewModel.releasePlayer()<br>        }<br>    }<br><br>    Column {<br>        Media3AndroidView(player)<br>        PlayerControls(player)<br>    }<br><br>}<br><br>@Composable<br>fun Media3AndroidView(player: ExoPlayer?) {<br>    AndroidView(<br>        modifier = Modifier.fillMaxWidth(),<br>        factory = { context -&gt;<br>            PlayerView(context).apply {<br>                this.player = player<br>            }<br>        },<br>        update = { playerView -&gt;<br>            playerView.player = player<br>        }<br>    )<br>}</pre><p>4- <strong>Create PlayerControls Composable</strong></p><p>We can also create a PlayerControls composable<em> </em>in a separate file or the same file if preferred<em> </em>to provide buttons for play, pause, and seek functionalities<em>:</em></p><pre>@Composable<br>fun PlayerControls(player: ExoPlayer?) {<br>    Column(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .padding(24.dp),<br>        horizontalAlignment = Alignment.Start,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Button(onClick = { player?.playWhenReady = true }) {<br>            Text(&quot;Play&quot;)<br>        }<br>        Button(onClick = { player?.playWhenReady = false }) {<br>            Text(&quot;Pause&quot;)<br>        }<br><br>        Button(onClick = {<br>            player?.seekTo(player.currentPosition - 10_000) // Seek backward 10 seconds<br>        }) {<br>            Text(&quot;Seek -10s&quot;)<br>        }<br>        Button(onClick = {<br>            player?.seekTo(player.currentPosition + 10_000) // Seek forward 10 seconds<br>        }) {<br>            Text(&quot;Seek +10s&quot;)<br>        }<br>    }<br>}</pre><p>5- <strong>Use Media3PlayerView Composable in your app</strong>:</p><p>Now we can call our Media3PlayerView composable in our view.</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            YourAppTheme {<br>                Surface(color = MaterialTheme.colorScheme.background) {<br>                    Media3PlayerView(<br>                        // replace your own videoUrl here.<br>                        videoUrl = &quot;https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4&quot;<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>6-<strong> Add Internet permission to AndroidManifest file:</strong></p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWzyfkeilwlawPPXJufDAQ.png" /></figure><p>You can find full code implementation here:</p><p><a href="https://github.com/akhorasani/Media3Player">GitHub - akhorasani/Media3Player</a></p><p>By following these steps and utilizing the provided code snippets, you can effectively integrate ExoPlayer into your Jetpack Compose application and handle any errors that may occur during playback.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c033acd016" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Foreground Services in Android Apps]]></title>
            <link>https://medium.com/@khorassani64/implementing-foreground-services-in-android-apps-df2d66535121?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/df2d66535121</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 04:31:30 GMT</pubDate>
            <atom:updated>2025-03-16T02:18:27.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Foreground services are a type of service in Android that performs operations that are noticeable to the user. These services must display a notification to let the user know that the service is running, which cannot be dismissed until the service stops or is no longer a foreground service. Foreground services are commonly used for tasks that need to run in the background while the user is actively aware of them, such as music playback, file downloads, or navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqURY8kygtNtGUSEJDPN9Q.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/geralt-9301/">geralt</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><p><strong>Creating a Foreground Service</strong></p><p>To create a foreground service, follow these steps:</p><p><strong>1- Create the Service Class</strong></p><p>First, we have to create a class that extends Service and override the necessary methods.</p><pre>class MyForegroundService : Service() {<br><br>    override fun onBind(intent: Intent?): IBinder? {<br>        return null<br>    }<br><br>    override fun onCreate() {<br>        super.onCreate()<br>    }<br><br><br>// This is triggered when another android component sends an Intent to this running service<br>    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br><br>// Do the work that the service needs to do here<br>        When (intent?.action) {<br>            Actions.START.toString() -&gt; {<br>                startForegroundService() // This method tells the system that a service will become a foreground service soon.<br>                start() // Call start() to create the notification and start in foreground<br>            }<br>            Actions.STOP.toString() -&gt; stopSelf()<br>        }<br><br>        return super.onStartCommand(intent, flags, startId)<br>    }<br><br>    enum class Actions {<br>        START, STOP<br>    }<br><br>    private fun start() {<br><br>        val notification = NotificationCompat.Builder(this, &quot;ForegroundServiceChannelId&quot;)<br>            .setSmallIcon(R.drawable.ic_notification)<br>            .setContentTitle(&quot;Foreground Service&quot;)<br>            .setContentText(&quot;Foreground service is running&quot;)<br>            .build()<br><br>        // Start the service in the foreground<br>        startForeground(1, notification)<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        // Clean up any resources here<br>    }<br>}</pre><p><strong>2- Create ForegroundServiceChannelId in Application class</strong></p><p>Then for android 8.0 and above we have to create our notification channel in our application class.</p><pre>Class MyApplication: Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br><br>        // Create the notification channel (required for Android 8.0 and above)<br>        if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.O) {<br>            val channel = NotificationChannel(<br>                &quot;ForegroundServiceChannelId&quot;,<br>                &quot;Foreground Service Channel&quot;,<br>                NotificationManager.IMPORTANCE_DEFAULT<br>            )<br>        // service provided by Android Operating system to show notification outside of our app<br>        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br>        notificationManager.createNotificationChannel(channel)<br>        }<br>    }<br>}</pre><p><strong>3- Register the Service in the Manifest</strong></p><p>Then we have to register our Application class and also declare our service and give permission to it in our AndroidManifest.xml file:</p><pre>&lt;manifest&gt;<br><br>   &lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot; /&gt;<br>   &lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot; /&gt;<br><br><br>   &lt;application<br>       android:name=&quot;.MyApplication&quot;<br>       ...<br>   &gt;<br>       &lt;activity<br>           ...<br>       &lt;/activity&gt;<br>       &lt;service android:name=&quot;.MyForegroundService&quot; android:foregroundServiceType=&quot;mediaPlayback&quot; /&gt;<br>   &lt;/application&gt;<br><br>&lt;/manifest&gt;</pre><blockquote>Please note that It’s important to mention the foreground service type because Android is quite restrictive about it.</blockquote><p><strong>4- Start and Stop the Foreground Service</strong></p><p>Now we can write our requestPermission code and also Start and Stop our foreground service from our Main Activity or another component.</p><pre>class MainActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.T) {   <br>            ActivityCompat.requestPermissions(<br>                this,<br>                arrayOf(Manifest.permission.POST_NOTIFICATION),<br>                requestCode: 0<br>            )<br>        }<br><br>        setContentView(R.layout.activity_main)<br><br>        // Start the foreground service<br>        Button(onClick = {        <br>           Intent(applicationContext, MyForegroundService::class.java).also{<br>               it.action = MyForegroundService.Actions.START.toString()<br>               startService(it)<br>           }<br>        }) {<br>               Text(text = “Start Service”)<br>           }<br><br>        // Stop the foreground service<br>        Button(onClick = {        <br>           Intent(applicationContext, MyForegroundService::class.java).also{<br>               it.action = MyForegroundService.Actions.STOP.toString()<br>               startService(it)<br>           }<br>        }) {<br>               Text(text = “Stop Service”)<br>           }<br><br>    }<br>       <br>}</pre><p><strong>Summary</strong></p><p>Foreground services are essential for long-running tasks that require user awareness and should not be easily killed by the system. By creating a foreground service, you ensure that your service continues to run and the user is always informed about its activity through a persistent notification. This is especially important for tasks such as media playback, navigation, and ongoing data uploads or downloads.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df2d66535121" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SignalR for Real-Time Communication in Android]]></title>
            <link>https://medium.com/@khorassani64/implementing-signalr-for-real-time-communication-in-android-bb44ef8d0c2b?source=rss-7cc283c33fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb44ef8d0c2b</guid>
            <dc:creator><![CDATA[Ali Khavari Khorasani]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 17:19:42 GMT</pubDate>
            <atom:updated>2024-09-13T15:36:23.765Z</atom:updated>
            <content:encoded><![CDATA[<p>SignalR is a real-time communication library for ASP.NET developers, which allows bi-directional communication between server and client. It’s particularly useful for applications requiring live updates, such as chat apps, live sports scores, and real-time dashboards. In Android Kotlin programming, you can use the SignalR client library to connect to a SignalR server and exchange messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htOUprFTV6zi46kVtSN_sw.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/">pixabay</a></figcaption></figure><p>Here’s a basic example of how you might use SignalR in an Android Kotlin app:</p><p>1- Add the SignalR client library to your build.gradle file:</p><pre>implementation &#39;com.microsoft.signalr:signalr:5.0.4&#39;</pre><p>2- Connect to a SignalR hub in your activity or fragment:</p><pre>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var hubConnection: HubConnection<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        // Build the SignalR hub connection<br>        hubConnection = HubConnectionBuilder.create(&quot;your_hub_url&quot;)<br>            .withTransport(com.microsoft.signalr.TransportEnum.LONG_POLLING)<br>            .build()<br><br>        // Start the connection<br>        hubConnection.start().blockingAwait()<br><br>        // Register a handler for incoming messages<br>        hubConnection.on(&quot;ReceiveMessage&quot;) { user: String, message: String -&gt;<br>            runOnUiThread {<br>                // Handle the incoming message<br>                textView.text = &quot;$user: $message&quot;<br>            }<br>        }<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        // Stop the connection when the activity is destroyed<br>        hubConnection.stop()<br>    }<br>}</pre><p>3- Send messages to the hub:</p><pre>// Send a message to the hub<br>hubConnection.send(&quot;SendMessage&quot;, &quot;user&quot;, &quot;Hello, SignalR!&quot;)</pre><p>4- Reconnecting and Error Handling</p><p>SignalR provides events for connection lifecycle management, which you can use to handle reconnections and errors:</p><pre>// Reconnect on closed connection<br>hubConnection.onClosed { exception -&gt;<br>    runOnUiThread {<br>        // Handle connection closed<br>        if (exception != null) {<br>            Log.e(&quot;SignalR&quot;, &quot;Connection closed with error: ${exception.message}&quot;)<br>        } else {<br>            Log.d(&quot;SignalR&quot;, &quot;Connection closed&quot;)<br>        }<br>        // Attempt to reconnect<br>        hubConnection.start().blockingAwait()<br>    }<br>}<br><br>// Handle connection errors<br>hubConnection.on(&quot;ConnectionError&quot;) { error: String -&gt;<br>    runOnUiThread {<br>        // Handle the connection error<br>        Log.e(&quot;SignalR&quot;, &quot;Connection error: $error&quot;)<br>    }<br>}</pre><p>5- Sending Complex Objects</p><p>You can send complex objects to the hub by defining data classes:</p><pre>data class ChatMessage(val user: String, val message: String)<br><br>hubConnection.send(&quot;SendChatMessage&quot;, ChatMessage(&quot;user&quot;, &quot;Hello, SignalR!&quot;))</pre><p>This is a basic example to get you started with SignalR in Android Kotlin programming. You’ll need to replace “your_hub_url” with the actual URL of your SignalR hub, and you can define your own hub methods and messages as needed for your application.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb44ef8d0c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>