<?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 alanrb on Medium]]></title>
        <description><![CDATA[Stories by alanrb on Medium]]></description>
        <link>https://medium.com/@alanrb?source=rss-49b08bc0b7af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2j_Ffmvhtws_oUBoYEod3Q.jpeg</url>
            <title>Stories by alanrb on Medium</title>
            <link>https://medium.com/@alanrb?source=rss-49b08bc0b7af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:27:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alanrb/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, Signing, and Verifying Docker Images for Golang Apps with GitLab CI/CD, Kaniko, and…]]></title>
            <link>https://alanrb.medium.com/building-signing-and-verifying-docker-images-for-golang-apps-with-gitlab-ci-cd-kaniko-and-3f923e31f15d?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f923e31f15d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[azure-container-registry]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 14:12:18 GMT</pubDate>
            <atom:updated>2025-03-17T14:32:35.288Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building, Signing, and Verifying Docker Images for Golang Apps with GitLab CI/CD, Kaniko, and Cosign</h3><p>In software development, CI/CD pipelines are essential for automating builds, tests, and deployments. When working with containerized applications, security is a top priority. This article will guide you through setting up a <strong>GitLab CI/CD pipeline</strong> for a Golang application, using <strong>Kaniko</strong> to build Docker images and <strong>Cosign</strong> to sign and verify them for enhanced security.</p><blockquote>By the end of this article, you’ll have a fully automated pipeline that:<br>1. Builds a Docker image for your Golang app using Kaniko.<br>2. Signs the image using Cosign.<br>3. Verifies the signed image before deployment.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0w7kcmhHRQ5FsOcXPQMrcQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hdbernd?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Bernd 📷 Dittrich</a> on <a href="https://unsplash.com/photos/a-couple-of-cargo-containers-sitting-next-to-each-other-l70397AVgCI?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><strong>Key Takeaways</strong><br>- How to set up a GitLab CI/CD pipeline for a Golang application.<br>- Using <strong>Kaniko</strong> to build Docker images without a Docker daemon.<br>- Signing and verifying Docker images with <strong>Cosign</strong>.<br>- Storing sensitive keys securely using GitLab CI/CD variables.<br>- Environment-specific configurations for staging and production.</p><p><strong>Prerequisites</strong><br>Before we begin, ensure you have:</p><ul><li>A <strong>GitLab account</strong> and a Golang project.</li><li>Access to an <strong>Azure Container Registry (ACR)</strong> or any other container registry.</li><li>Basic knowledge of Docker, GitLab CI/CD, and Kubernetes.</li></ul><h4><strong>Step 1: Set Up Your Golang Application</strong></h4><p>Let’s start with a simple Golang application. Here’s an example of a “<em>Hello, World!</em>” HTTP server:</p><pre>// main.go<br>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;net/http&quot;<br>)<br><br>func handler(w http.ResponseWriter, r *http.Request) {<br>	fmt.Fprintf(w, &quot;Hello, World!&quot;)<br>}<br><br>func main() {<br>	http.HandleFunc(&quot;/&quot;, handler)<br>	http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>Next, create a Dockerfile to containerize the application:</p><pre># Dockerfile<br>FROM golang:1.20-alpine AS builder<br>WORKDIR /app<br>COPY . .<br>RUN go build -o myapp .<br><br>FROM alpine:latest<br>WORKDIR /app<br>COPY --from=builder /app/myapp .<br>CMD [&quot;./myapp&quot;]</pre><h4>Step 2: Set Up GitLab CI/CD with Kaniko</h4><p><strong>Kaniko</strong> is a tool for building Docker images in Kubernetes or CI/CD pipelines without requiring a Docker daemon. Here’s how to configure your .gitlab-ci.yml file to build the Docker image using Kaniko and push it to Azure Container Registry (ACR):</p><pre># .gitlab-ci.yml<br>stages:<br>  - build<br>  - sign<br>  - verify<br><br>variables:<br>  IMAGE_NAME: &quot;my-golang-app&quot;<br>  ACR_NAME: &quot;myacr.azurecr.io&quot;<br>  IMAGE_TAG: &quot;latest&quot;<br><br>build:<br>  stage: build<br>  image:<br>    name: gcr.io/kaniko-project/executor:latest<br>    entrypoint: [&quot;&quot;]<br>  script:<br>    - echo &quot;Building Docker image with Kaniko&quot;<br>    - /kaniko/executor<br>      --context &quot;${CI_PROJECT_DIR}&quot;<br>      --dockerfile &quot;${CI_PROJECT_DIR}/Dockerfile&quot;<br>      --destination &quot;${ACR_NAME}/${IMAGE_NAME}:${IMAGE_TAG}&quot;</pre><h4>Step 3: Sign Docker Images with Cosign</h4><p>Cosign is a tool for signing and verifying container images. To sign your Docker image, follow these steps:</p><ol><li><strong>Generate Cosign Keys</strong>:</li></ol><pre>cosign generate-key-pair</pre><p>This will create cosign.key (private key) and cosign.pub (public key).</p><p><strong>2. Store Keys in GitLab CI/CD Variables:</strong></p><ul><li>Go to your GitLab project.</li><li>Navigate to <strong>Settings &gt; CI/CD &gt; Variables</strong>.</li><li>Add the following variables:</li></ul><p>COSIGN_PRIVATE_KEY: Paste the content of cosign.key.</p><p>COSIGN_PUBLIC_KEY: Paste the content of cosign.pub.</p><p><strong>3. Add a Signing Stage</strong>:<br>Update your .gitlab-ci.yml to include a sign stage:</p><pre>sign:<br>  stage: sign<br>  image:<br>    name: cgr.dev/chainguard/cosign:latest<br>    entrypoint: [&quot;&quot;]<br>  script:<br>    - echo &quot;Signing Docker image with Cosign&quot;<br>    - cosign sign --key $COSIGN_PRIVATE_KEY ${ACR_NAME}/${IMAGE_NAME}:${IMAGE_TAG}</pre><h4>Step 4: Verify Docker Images with Cosign</h4><p>Before deploying your image, verify its signature to ensure it hasn’t been tampered with. Add a verify stage to your pipeline:</p><pre>verify:<br>  stage: verify<br>  image:<br>    name: cgr.dev/chainguard/cosign:latest<br>    entrypoint: [&quot;&quot;]<br>  script:<br>    - echo &quot;Verifying Docker image with Cosign&quot;<br>    - cosign verify --key $COSIGN_PUBLIC_KEY ${ACR_NAME}/${IMAGE_NAME}:${IMAGE_TAG}</pre><h4>Step 5: Environment-Specific Variables</h4><p>For environment-specific configurations (e.g., staging vs. production), use GitLab CI/CD variables with environment scopes. Here’s how:</p><ol><li><strong>Add Environment-Specific Variables:</strong></li></ol><p>For staging:</p><ul><li><strong>Key</strong>: COSIGN_PRIVATE_KEY</li><li><strong>Value</strong>: staging-private-key</li><li><strong>Environment scope</strong>: staging</li></ul><p>For production:</p><ul><li><strong>Key</strong>: COSIGN_PRIVATE_KEY</li><li><strong>Value</strong>: production-private-key</li><li><strong>Environment scope</strong>: production</li></ul><p><strong>2. Update Your Pipeline:</strong></p><p>Use the variables in your .gitlab-ci.yml:</p><pre>deploy_to_staging:<br>  stage: deploy<br>  script:<br>    - echo &quot;Deploying to staging&quot;<br>    - cosign sign --key $COSIGN_PRIVATE_KEY ${ACR_NAME}/${IMAGE_NAME}:staging<br>  environment:<br>    name: staging<br>    url: https://staging.example.com<br><br>deploy_to_production:<br>  stage: deploy<br>  script:<br>    - echo &quot;Deploying to production&quot;<br>    - cosign sign --key $COSIGN_PRIVATE_KEY ${ACR_NAME}/${IMAGE_NAME}:production<br>  environment:<br>    name: production<br>    url: https://production.example.com</pre><h4>Conclusion</h4><p>By following this guide, you’ve set up a secure GitLab CI/CD pipeline for your Golang application. Using <strong>Kaniko</strong> and <strong>Cosign</strong>, you can now build, sign, and verify Docker images with confidence. This approach ensures that your containerized applications are secure and ready for deployment in any environment. For more information, check out the official documentation:</p><ul><li><a href="https://github.com/GoogleContainerTools/kaniko">Kaniko Documentation</a></li><li><a href="https://github.com/sigstore/cosign">Cosign Documentation</a></li><li><a href="https://docs.gitlab.com/ee/ci/">GitLab CI/CD Documentation</a></li></ul><h4>Example Code Repository</h4><p>You can find the complete example code, including Dockerfile, and .gitlab-ci.yml, in this <a href="https://github.com/alanrb/cosign/tree/main">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f923e31f15d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a State Machine in Java for Backend Systems]]></title>
            <link>https://alanrb.medium.com/implementing-a-state-machine-in-java-for-backend-systems-26bd7e724108?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/26bd7e724108</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[state-machine]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 15:30:11 GMT</pubDate>
            <atom:updated>2025-03-14T15:30:11.319Z</atom:updated>
            <content:encoded><![CDATA[<p>State machines are a powerful tool for modeling systems with distinct states and transitions. They are particularly useful in backend development for managing workflows, processes, or any system where the application’s behavior depends on its current state. In this article, we’ll walk through how to implement a simple state machine in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0KXYlUvHl5LymBgcSf1zEA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@imsidney?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Sidney Ding</a> on <a href="https://unsplash.com/photos/a-room-with-two-televisions-and-a-keyboard-ojU3-VZJeJg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>What is a State Machine?</p><p>A state machine is a computational model used to design systems that transition between predefined states based on events or inputs. It consists of:</p><ul><li><strong>States</strong>: The distinct conditions the system can be in.</li><li><strong>Events</strong>: Triggers that cause transitions between states.</li><li><strong>Transitions</strong>: Rules that define how the system moves from one state to another.</li></ul><p>For example, in an order processing system, states could be PENDING, PROCESSING, SHIPPED, and CANCELLED, with events like PLACE_ORDER, SHIP_ORDER, and CANCEL_ORDER.</p><h3>Why Use a State Machine?</h3><p>State machines help:</p><ul><li><strong>Simplify complex logic</strong>: By breaking down behavior into states and transitions.</li><li><strong>Improve maintainability</strong>: States and transitions are explicit and easy to modify.</li><li><strong>Prevent invalid states</strong>: Ensure the system only transitions to valid states.</li></ul><h3>Implementing a State Machine in Java</h3><p>Let’s implement a simple state machine in Java step by step.</p><h4>Step 1: Define the States</h4><p>First, define the possible states using an enum:</p><pre>public enum State {<br>    START,<br>    PROCESSING,<br>    COMPLETED,<br>    ERROR<br>}</pre><h4>Step 2: Define the Events</h4><p>Next, define the events that trigger transitions between states:</p><pre>public enum Event {<br>    BEGIN_PROCESSING,<br>    FINISH_PROCESSING,<br>    FAIL<br>}</pre><h4>Step 3: Create the State Machine Class</h4><p>Now, create a class to manage the state machine. This class will handle transitions and maintain the current state.</p><pre>import java.util.EnumMap;<br>import java.util.Map;<br><br>public class StateMachine {<br>    private State currentState;<br>    private Map&lt;State, Map&lt;Event, State&gt;&gt; transitions;<br><br>    public StateMachine() {<br>        this.currentState = State.START; // Initial state<br>        this.transitions = new EnumMap&lt;&gt;(State.class);<br>        initializeTransitions();<br>    }<br><br>    private void initializeTransitions() {<br>        // Define transition rules<br>        transitions.put(State.START, new EnumMap&lt;&gt;(Event.class));<br>        transitions.get(State.START).put(Event.BEGIN_PROCESSING, State.PROCESSING);<br><br>        transitions.put(State.PROCESSING, new EnumMap&lt;&gt;(Event.class));<br>        transitions.get(State.PROCESSING).put(Event.FINISH_PROCESSING, State.COMPLETED);<br>        transitions.get(State.PROCESSING).put(Event.FAIL, State.ERROR);<br><br>        transitions.put(State.COMPLETED, new EnumMap&lt;&gt;(Event.class)); // No further transitions<br>        transitions.put(State.ERROR, new EnumMap&lt;&gt;(Event.class)); // No further transitions<br>    }<br><br>    public State getCurrentState() {<br>        return currentState;<br>    }<br><br>    public void processEvent(Event event) {<br>        Map&lt;Event, State&gt; stateTransitions = transitions.get(currentState);<br>        if (stateTransitions != null &amp;&amp; stateTransitions.containsKey(event)) {<br>            currentState = stateTransitions.get(event);<br>        } else {<br>            throw new IllegalStateException(&quot;Invalid event: &quot; + event + &quot; for current state: &quot; + currentState);<br>        }<br>    }<br>}</pre><h4>Step 4: Use the State Machine</h4><p>You can now use the state machine in your backend logic. Here’s an example:</p><pre>public class BackendService {<br>    private StateMachine stateMachine;<br><br>    public BackendService() {<br>        this.stateMachine = new StateMachine();<br>    }<br><br>    public void startProcessing() {<br>        stateMachine.processEvent(Event.BEGIN_PROCESSING);<br>        System.out.println(&quot;State: &quot; + stateMachine.getCurrentState());<br>    }<br><br>    public void finishProcessing() {<br>        stateMachine.processEvent(Event.FINISH_PROCESSING);<br>        System.out.println(&quot;State: &quot; + stateMachine.getCurrentState());<br>    }<br><br>    public void failProcessing() {<br>        stateMachine.processEvent(Event.FAIL);<br>        System.out.println(&quot;State: &quot; + stateMachine.getCurrentState());<br>    }<br><br>    public static void main(String[] args) {<br>        BackendService service = new BackendService();<br>        service.startProcessing(); // State: PROCESSING<br>        service.finishProcessing(); // State: COMPLETED<br>    }<br>}</pre><h4>Step 5: Advanced Features (Optional)</h4><p>For more complex use cases, consider adding:</p><ol><li><strong>Actions on Transitions</strong>: Execute code during transitions.</li><li><strong>Guard Conditions</strong>: Add conditions to allow or block transitions.</li><li><strong>Persistence</strong>: Save the current state to a database for recovery.</li><li><strong>Libraries</strong>: Use libraries like <a href="https://projects.spring.io/spring-statemachine/">Spring State Machine</a> or <a href="https://github.com/hekailiang/squirrel">Squirrel Foundation</a> for advanced functionality.</li></ol><p>Here’s an example of adding actions:</p><pre>public class StateMachine {<br>    // ... (previous code)<br><br>    private Map&lt;State, Map&lt;Event, Runnable&gt;&gt; actions;<br><br>    public StateMachine() {<br>        // ... (previous initialization)<br>        this.actions = new EnumMap&lt;&gt;(State.class);<br>        initializeActions();<br>    }<br><br>    private void initializeActions() {<br>        actions.put(State.START, new EnumMap&lt;&gt;(Event.class));<br>        actions.get(State.START).put(Event.BEGIN_PROCESSING, () -&gt; System.out.println(&quot;Starting processing...&quot;));<br><br>        actions.put(State.PROCESSING, new EnumMap&lt;&gt;(Event.class));<br>        actions.get(State.PROCESSING).put(Event.FINISH_PROCESSING, () -&gt; System.out.println(&quot;Processing completed!&quot;));<br>        actions.get(State.PROCESSING).put(Event.FAIL, () -&gt; System.out.println(&quot;Processing failed!&quot;));<br>    }<br><br>    public void processEvent(Event event) {<br>        Map&lt;Event, State&gt; stateTransitions = transitions.get(currentState);<br>        if (stateTransitions != null &amp;&amp; stateTransitions.containsKey(event)) {<br>            // Execute action if defined<br>            if (actions.get(currentState) != null &amp;&amp; actions.get(currentState).get(event) != null) {<br>                actions.get(currentState).get(event).run();<br>            }<br>            currentState = stateTransitions.get(event);<br>        } else {<br>            throw new IllegalStateException(&quot;Invalid event: &quot; + event + &quot; for current state: &quot; + currentState);<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>State machines are a great way to manage complex workflows in backend systems. By breaking down behavior into states and transitions, you can create systems that are easier to understand, maintain, and extend. In this article, we implemented a simple state machine in Java and explored how to use it in a backend service.</p><p>For more advanced use cases, consider leveraging existing libraries or adding features like actions, guard conditions, and persistence.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26bd7e724108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Flutter to existing app]]></title>
            <link>https://alanrb.medium.com/add-flutter-to-existing-app-cd0d16883437?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0d16883437</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Sun, 10 Jul 2022 08:48:50 GMT</pubDate>
            <atom:updated>2022-07-10T09:01:58.638Z</atom:updated>
            <content:encoded><![CDATA[<p># Add Flutter to existing app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*88B7euh79gQZYJ4mEFvT1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nateggrant">Nate Grant</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Add-to-app</h3><p>It’s sometimes not practical to rewrite your entire application in Flutter all at once. For those situations, Flutter can be integrated into your existing application piecemeal, as a library or module. That module can then be imported into your Android or iOS (currently supported platforms) app to render a part of your app’s UI in Flutter. Or, just to run shared Dart logic.</p><p>In a few steps, you can bring the productivity and the expressiveness of Flutter into your own app.</p><p>The add-to-app feature supports integrating multiple instances of any screen size. This can help scenarios such as a hybrid navigation stack with mixed native and Flutter screens, or a page with multiple partial-screen Flutter views.</p><p>Having multiple Flutter instances allows each instance to maintain independent application and UI state while using minimal memory resources. See more in the <a href="https://docs.flutter.dev/development/add-to-app/multiple-flutters">multiple Flutters</a> page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*ITgbsYyeKMBD5HOIiqiVYw.png" /></figure><p>Let’s assume that you have an existing app at some/path/EVChargingStationAndroid, and that you want your Flutter project as a sibling:</p><pre>cd some/path/<br>$ flutter create -t module --org com.github.alanrb ev_charging_station_flutter</pre><pre>some/path/<br>├── ev_charging_station_flutter/<br>│   └── build/host/outputs/repo<br>│   └── .ios/<br>│       └── Flutter/<br>│         └── podhelper.rb<br>└── EVChargingStationAndroid/<br>│   └── settings.gradle<br>└── EVChargingStationiOS/<br>│   └── Podfile<br>│   └── Flutter<br>│       └── Debug<br>│       └── Release</pre><h3>Android</h3><h4>Setup — Depend on the Android Archive (AAR)</h4><p>Let’s assume you built a Flutter module at some/path/ev_charging_station_flutter, and then run:</p><pre>cd some/path/ev_charging_station_flutter<br>flutter build aar</pre><p>You will get the output:</p><pre>💪 Building with sound null safety 💪</pre><pre>Running Gradle task &#39;assembleAarDebug&#39;...                          43.4s<br>✓ Built build/host/outputs/repo.<br>Running Gradle task &#39;assembleAarProfile&#39;...                        40.8s<br>✓ Built build/host/outputs/repo.<br>Running Gradle task &#39;assembleAarRelease&#39;...                        41.3s<br>✓ Built build/host/outputs/repo.</pre><pre>Consuming the Module<br>  1. Open &lt;host&gt;/app/build.gradle<br>  2. Ensure you have the repositories configured, otherwise add them:</pre><pre>      String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: &quot;https://storage.googleapis.com&quot;<br>      repositories {<br>        maven {<br>            url &#39;/some/path/EV-Charging-Station/ev_charging_station_flutter/build/host/outputs/repo&#39;<br>        }<br>        maven {<br>            url &quot;$storageUrl/download.flutter.io&quot;<br>        }<br>      }</pre><pre>  3. Make the host app depend on the Flutter module:</pre><pre>    dependencies {<br>      debugImplementation &#39;com.github.alanrb.ev_charging_station_flutter:flutter_debug:1.0&#39;<br>      profileImplementation &#39;com.github.alanrb.ev_charging_station_flutter:flutter_profile:1.0&#39;<br>      releaseImplementation &#39;com.github.alanrb.ev_charging_station_flutter:flutter_release:1.0&#39;<br>    }<br></pre><pre>  4. Add the `profile` build type:</pre><pre>    android {<br>      buildTypes {<br>        profile {<br>          initWith debug<br>        }<br>      }<br>    }</pre><pre>To learn more, visit <a href="https://flutter.dev/go/build-aar">https://flutter.dev/go/build-aar</a></pre><p>Let’s open the <a href="https://github.com/alanrb/EV-Charging-Station/blob/main/EVChargingStationAndroid/settings.gradle">settings.gradle</a> and edit the section under dependencyResolutionManagement</p><pre>pluginManagement {  <br>  <br>  repositories {  <br>  gradlePluginPortal()  <br>        google()  <br>        mavenCentral()  <br>    }  <br>}  <br>dependencyResolutionManagement {  <br>  repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)  <br>    String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: &quot;https://storage.googleapis.com&quot;  <br>  repositories {  <br>  google()  <br>        mavenCentral()  <br>        maven {  <br>  url &#39;../ev_charging_station_flutter/build/host/outputs/repo&#39;  <br>  }  <br>  maven {  <br>  url &quot;$storageUrl/download.flutter.io&quot;  <br>  }  <br> }}  <br>rootProject.name = &quot;EVChargingStation&quot;  <br>include &#39;:app&#39;</pre><p>Next step, open <a href="https://github.com/alanrb/EV-Charging-Station/blob/main/EVChargingStationAndroid/app/build.gradle">app/build.gradle</a> in host app EVChargingStationAndroid so that it includes the dependency:</p><pre>debugImplementation &#39;com.github.alanrb.ev_charging_station_flutter:flutter_debug:1.0&#39;  <br>profileImplementation &#39;com.github.alanrb.ev_charging_station_flutter:flutter_profile:1.0&#39;  <br>releaseImplementation &#39;com.github.alanrb.ev_charging_station_flutter:flutter_release:1.0&#39;</pre><h4>Implement FlutterFragmentActivity from your app</h4><ul><li>In Application:</li></ul><pre>class App: Application() {  <br>    lateinit var engines: FlutterEngineGroup  <br>  <br>    override fun onCreate() {  <br>        super.onCreate()  <br>        engines = FlutterEngineGroup(this)  <br>    }  <br>}</pre><ul><li>Create <a href="https://github.com/alanrb/EV-Charging-Station/blob/main/EVChargingStationAndroid/app/src/main/java/com/github/alanrb/evchargingstation/ui/main/EngineBindings.kt">EngineBindings</a> to binds a FlutterEngine instance and a channel for communicating with that engine.</li></ul><pre>class MainActivity : FlutterFragmentActivity() {  <br>    private val engineBindings: EngineBindings by lazy {  <br>	    EngineBindings(activity = this, entrypoint = &quot;main&quot;, channelName = &quot;multiple-flutters&quot;)  <br>    }  <br>  <br>    override fun onCreate(savedInstanceState: Bundle?) {  <br>        super.onCreate(savedInstanceState)  <br>        engineBindings.attach { call, result -&gt;<br>	        when (call.method) {  <br>                &quot;station_show_details&quot; -&gt; {<br>	                // Handle event<br>	                result.success(null)  <br>                }  <br>                else -&gt; {  <br>                    result.notImplemented()  <br>                }  <br>            }  <br>        }  <br>  }  <br>  <br>    override fun onDestroy() {  <br>        super.onDestroy()  <br>        engineBindings.detach()  <br>    }  <br>  <br>    override fun provideFlutterEngine(context: Context): FlutterEngine {  <br>        return engineBindings.engine  <br>  }  <br>}</pre><h3>iOS</h3><h4>Setup — Embed application and plugin frameworks in Xcode and Flutter framework with CocoaPods</h4><h4>Setting up CocoaPods</h4><ul><li>In case your host project doesn’t already use <strong>CocoaPods</strong>, you need to create a Podfile. If you already have a <strong>Podfile</strong> created in your iOS project, then you can skip the first step.</li><li>Run this command from the iOS project directory:</li></ul><pre>cd some/path/EVChargingStationiOS<br>pod init<br>pod install</pre><ul><li>Alternatively, instead of distributing the large <strong>Flutter.framework</strong> to other developers, machines, or continuous integration systems, you can instead generate <strong>Flutter</strong> as CocoaPods podspec. This produces a Flutter.podspec instead of an engine <strong>Flutter.framework</strong>. The <strong>App.framework</strong> and plugin frameworks will be generated as described in <a href="https://docs.flutter.dev/development/add-to-app/ios/project-setup#option-b---embed-frameworks-in-xcode">Option B</a>.</li></ul><pre>flutter build ios-framework --cocoapods --output=../EVChargingStationiOS/Flutter</pre><p>Output:</p><pre>Building frameworks for com.github.alanrb.evChargingStationFlutterSDK in debug mode...<br> ├─Creating Flutter.podspec...                                       2ms<br> ├─Building App.xcframework...                                     33.6s<br>Running pod install...                                           1,546ms<br> ├─Building plugins...                                             12.7s<br> └─Moving to ../EVChargingStationiOS/Flutter/Debug                 132ms<br>Building frameworks for com.github.alanrb.evChargingStationFlutterSDK in release mode...<br> ├─Creating Flutter.podspec...                                       1ms<br> ├─Building App.xcframework...                                     60.2s<br> ├─Building plugins...                                             13.7s<br> └─Moving to ../EVChargingStationiOS/Flutter/Release               162ms<br>Frameworks written to /some/path/EV-Charging-Station/ev_charging_station_flutter/../EVChargingStationiOS/Flutter.</pre><p>Host apps EVChargingStationiOS using CocoaPods to add Flutter to Podfile:</p><pre>pod &#39;Flutter&#39;, :podspec =&gt; &#39;Flutter/Debug/Flutter.podspec&#39;<br>or<br>pod &#39;Flutter&#39;, :podspec =&gt; &#39;Flutter/Release/Flutter.podspec&#39;</pre><p>Run pod install from some/path/EVChargingStationiOS again and you should see Flutter framework pods being installed.</p><p>You can now open the EVChargingStationiOS project in Xcode again by directing Xcode to the some/path/EVChargingStationiOS/EVChargingStationiOS.xcworkspace file, (<strong>not</strong> the .xcodeproj file!).</p><p>Your project layout in Xcode now looks as follows:</p><pre>some/path/<br>├── ev_charging_station_flutter/<br>│   └── build/host/outputs/repo<br>│   └── .ios/<br>│       └── Flutter/<br>│         └── podhelper.rb<br>└── EVChargingStationAndroid/<br>│   └── settings.gradle<br>└── EVChargingStationiOS/<br>│   └── Podfile<br>│   └── Pods/<br>│   └── Flutter/<br>│       └── Debug<br>│       └── Release</pre><h4>Add a build phase for building the Dart code</h4><ul><li>For example, you can drag the frameworks from some/path/EVChargingStationiOS/Flutter/Release/ in Finder into your target’s <strong>Build Settings &gt; Build Phases &gt; Link Binary With Libraries</strong>.</li><li>In the target’s build settings, add $(PROJECT_DIR)/Flutter/Release/ to the <strong>Framework Search Paths</strong> (FRAMEWORK_SEARCH_PATHS).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*oiBt6WGUy7FRVI9EhztN7A.png" /></figure><ul><li>By <strong>Build Settings &gt; User-defined</strong>, add a FLUTTER_ROOT as the Flutter sdk path.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*MX5v4FFX9hM6gUm9.png" /></figure><ul><li>And then select the <strong>Build Phases</strong> tab, add Thin Binary script as follows:</li></ul><pre>/bin/sh &quot;$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh&quot; embed_and_thin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*j48vcunC1R9YHILj.png" /></figure><h4>Implement FlutterViewController from your app</h4><p>To launch a Flutter screen from an existing iOS, you start a <a href="https://api.flutter.dev/objcdoc/Classes/FlutterEngine.html">FlutterEngine</a> and a <a href="https://api.flutter.dev/objcdoc/Classes/FlutterViewController.html">FlutterViewController</a>.</p><blockquote><em>The </em><em>FlutterEngine serves as a host to the Dart VM and your Flutter runtime, and the </em><em>FlutterViewController attaches to a </em><em>FlutterEngine to pass UIKit input events into Flutter and to display frames rendered by the </em><em>FlutterEngine.</em></blockquote><p>In AppDelegate:</p><pre>import Flutter<br>@main<br>class  AppDelegate: UIResponder, UIApplicationDelegate {<br>	let engines = FlutterEngineGroup(name: &quot;multiple-flutters-group&quot;, project: nil)</pre><pre>	func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>		return  true<br>	}<br>}</pre><pre>import Flutter<br>import FlutterPluginRegistrant</pre><pre>class MainVC: FlutterViewController {<br>	private var channel: FlutterMethodChannel?<br>	init(withEntrypoint entryPoint: String?) {<br>		let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate<br>		let newEngine = appDelegate.engines.makeEngine(withEntrypoint: entryPoint, libraryURI: nil)<br>		GeneratedPluginRegistrant.register(with: newEngine)<br>		super.init(engine: newEngine, nibName: nil, bundle: nil)<br>	}<br>	<br>	required init(coder aDecoder: NSCoder) {<br>		fatalError(&quot;init(coder:) has not been implemented&quot;)<br>	}</pre><pre>	override func  viewDidLoad() {<br>		super.viewDidLoad()<br>		channel = FlutterMethodChannel(name: &quot;multiple-flutters&quot;, binaryMessenger:self.engine!.binaryMessenger)<br>		channel!.setMethodCallHandler { (call: FlutterMethodCall, result: **@escaping** FlutterResult) in<br>			if call.method == &quot;station_show_details&quot; {<br>				// Handle event<br>				result(nil)<br>			} else {<br>				result(FlutterMethodNotImplemented)<br>			}<br>		}<br>	}<br>}</pre><p><a href="https://github.com/alanrb/EV-Charging-Station">GitHub - alanrb/EV-Charging-Station</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0d16883437" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One year into coronavirus - social distancing]]></title>
            <link>https://alanrb.medium.com/one-year-into-coronavirus-social-distancing-671eb3653eac?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/671eb3653eac</guid>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 03:16:04 GMT</pubDate>
            <atom:updated>2021-06-02T03:46:47.511Z</atom:updated>
            <content:encoded><![CDATA[<p>The year 2020 is hardly the first time the world has been struck by a pandemic. My office is temporarily closed and staff are working remotely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4I1bsbPNdaxnPkSyUQ-7w.jpeg" /><figcaption>Last day in the office 2020</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0hAmq23gj04RSfcOjQW-g.jpeg" /><figcaption>Extra Corona</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoTXDd7jcRg2t24y_oDlsA.jpeg" /><figcaption>Setup working space @home</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKBi9z7rGSSIldrwCD_pjg.jpeg" /><figcaption>look after kid as well</figcaption></figure><p>Since 2021, The situation is getting better, we are all looking forward to things “getting back to normal” as soon as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyN5pPoKTKKjndb2s7P0Yg.jpeg" /><figcaption>First day back @the office 2021</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzBXiiadSuFPcNUKOWPZ4Q.jpeg" /><figcaption>Traffic after rain</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w3fZzq8h-lzFFYV1q7w7JA.jpeg" /><figcaption>a day as usual</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBOBBTrwlhDq1h4NCnzMyw.jpeg" /><figcaption>Lunch time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ma6B5nPSprHbastKr1J40w.jpeg" /><figcaption>Team scheduling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qN7Ok9EO4Okw7MUA6t6wMg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dy9HKQJ1lOjLz-zA_ZmU6w.jpeg" /><figcaption>Go for dinner!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zkk_Cd_UPsUbQi7tW-8dA.jpeg" /><figcaption>Coffee break</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sf5YmLK71fyK-zV15XyRxA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJpk4-9zSHDlysgaqaatrA.jpeg" /><figcaption>Mango monster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8ZUPzmR_9FRim6qApCBTw.jpeg" /><figcaption>HVL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nH51GURoo3vjqZ_FNGSMUg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rzv8miGahFbxPlhF6tTDLA.jpeg" /><figcaption>There’s an interview =))</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdqgHvi5yIqP861blSPd5g.jpeg" /><figcaption>Team drinking!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCx7OhQKFDRq4ZTkSxiIOw.jpeg" /><figcaption>Way back home</figcaption></figure><p>Social distancing@2021 is here to stay for much more than a few weeks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvZBfRqfAEKe9t90LI3j0A.jpeg" /><figcaption>My apartment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcwwnFsdN-w5SxOt0vK1Wg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*A8O7h20Sp9yYAto_PPYeog.jpeg" /><figcaption>Go away from kid =))</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*B4Gy2udAWxFNQ4ZUSEC_2w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=671eb3653eac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Ktor in Android application]]></title>
            <link>https://alanrb.medium.com/using-ktor-in-android-application-c1bd51a1c105?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bd51a1c105</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ktor]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 06:35:40 GMT</pubDate>
            <atom:updated>2020-09-21T06:41:25.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iy8f3eKSDtf5CEneFw0qVA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kensuarez">Ken Suarez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Is Ktor?</h3><p>From <a href="https://ktor.io/docs/quickstart-index.html">official website</a>: “Ktor is a framework to easily build connected applications — web applications, HTTP services, mobile and browser applications. Modern connected applications need to be asynchronous to provide the best experience to users, and Kotlin coroutines provide awesome facilities to do it in an easy and straightforward way.”</p><p>It supports <a href="https://ktor.io/clients/http-client/multiplatform.html">multiplatform</a> projects.<em> </em>This article explores how to implement the framework in Android project.</p><h3>Implementation</h3><pre>def ktor_version = &#39;1.3.0&#39;<br><br><em>implementation</em> &quot;io.ktor:ktor-client-android:$ktor_version&quot;<br>// in your code, create the client<br><strong>// HttpClient</strong>(Android)<br><br><em>implementation</em> &quot;io.ktor:ktor-client-okhttp:$ktor_version&quot;<br>// in your code, create the client<br><strong>// HttpClient</strong>(Okhttp)<br><br><em>implementation</em> &quot;io.ktor:ktor-client-cio:$ktor_version&quot;<br>// in your code, create the client<br><strong>// HttpClient</strong>(CIO)<br><br>implementation &quot;io.ktor:ktor-client-serialization-jvm:$ktor_version&quot;</pre><h4>Building the client</h4><p>“Ktor HTTP Client has a common interface but allows to specify an engine that processes the network request. Different engines have different configurations, dependencies and supporting features.”<br>For Android, you can work with one of the following engines:</p><p><strong>CIO</strong><br>CIO (Coroutine-based I/O) is a Ktor implementation with no additional dependencies and is fully asynchronous. It only supports <strong>HTTP/1.x</strong> for now. CIO provides maxConnectionsCount and a endpointConfig for configuring.</p><p><strong>OkHttp</strong><br>There is a engine based on <a href="https://square.github.io/okhttp/">OkHttp</a></p><p><strong>Android</strong><br>The Android engine doesn’t have additional dependencies and uses a ThreadPool with a normal HttpURLConnection, to perform the requests.</p><p>For example, we use KotlinxSerializer to parse the JSON response (or other libraries like Gson, Jackson, etc).</p><pre>// You can replace CIO with your engine of choice<br>private val client = HttpClient(CIO) <strong>{<br>    </strong>install(JsonFeature) <strong>{<br>        </strong>serializer = KotlinxSerializer(Json.nonstrict)<br>    <strong>}<br>}</strong></pre><h4>Making Requests</h4><p>To make a <strong>GET/POST</strong> request, we have to use the <strong><em>get/post</em></strong> suspend function with a response data class and request URL.</p><pre>client.<strong>get</strong>&lt;ContactResult&gt;(&quot;https://randomuser.me/api/?results=25&quot;)</pre><p><strong>Headers</strong></p><p>To add headers into Ktor request, you can do:</p><pre>client.get&lt;ContactResult&gt;(&quot;https://randomuser.me/api/?results=25&quot;) <strong>{<br>    <em>headers</em></strong><em> </em><strong>{<br>        </strong>append(&quot;custom-header&quot;, &quot;header-value&quot;)<br>    <strong>}<br>}</strong></pre><p>You can take a look at sample on my github:<br><a href="https://github.com/alanrb/Ktor-Android-example">https://github.com/alanrb/Ktor-Android-example</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikhSBrQFJ4asDWXEtLbNVw.png" /></figure><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bd51a1c105" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiplatform Mobile (KMM). Part 1: Getting Started.]]></title>
            <link>https://alanrb.medium.com/multiplatform-mobile-kmm-part-1-getting-started-eed52ae443b0?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/eed52ae443b0</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[multiplatform]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 08:53:59 GMT</pubDate>
            <atom:updated>2020-09-20T15:20:38.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Multiplatform Mobile (KMM). Part 1: Getting Started.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StQAt2_1sCUcsgTK3_quTQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum">Claudio Schwarz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Kotlin Multiplatform Mobile ?</h3><p>With <a href="https://kotlinlang.org/lp/mobile/">Kotlin Multiplatform Mobile (KMM)</a>, you can build multiplatform mobile applications sharing code, such as business logic, connectivity, and more, between Android and iOS.</p><p>“You only need to write platform-specific code where it’s necessary, for example to implement a native UI or when working with platform-specific APIs.”</p><h3>How to set up your Kotlin Multiplatform project?</h3><p>Open Android Studio, install <strong>Kotlin Multiplatform Mobile</strong> plugin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FGViBHD3dH5xB8W4YKt7Q.png" /><figcaption>Kotlin Multiplatform Mobile plugin</figcaption></figure><p>In Android Studio, select <strong>File</strong> | <strong>New</strong> | <strong>New Project</strong>. Select <strong>KMM Application</strong> in the list of project templates, and click <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJea79vBhF408fV7b03hIw.png" /></figure><p>Fill information for your application, and click <strong>Next</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRtHs4_uTD8JNs-Y2nZW_w.png" /><figcaption>Application info</figcaption></figure><h3>Project structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*gvdteCs_VdAH7onuY1P_gQ.png" /></figure><p>A basic Kotlin Multiplatform Mobile(KMM) project consists of three components:</p><ul><li><em>Shared module</em> — a Kotlin module that contains common logic for both Android and iOS applications. Builds into an Android library and an iOS framework. Uses Gradle as a build system.</li><li><em>Android application</em> — a Kotlin module that builds into the Android application. Uses Gradle as a build system.</li><li><em>iOS application</em> — an Xcode project that builds into the iOS application.</li></ul><h4>Shared module</h4><p>The shared module contains the code that is common for Android and iOS applications. However, to implement the same logic on Android and iOS, you sometimes need to write two platform-specific versions of it. To handle such cases, Kotlin offers the <a href="https://kotlinlang.org/docs/mobile/connect-to-platform-specific-apis.html">expect/actual</a> mechanism. The source code of the shared module is organized in three source sets accordingly:</p><ul><li>commonMain stores the code that works on both platforms, including the <strong>expect</strong> declarations</li><li>androidMain stores Android-specific parts, including <strong>actual</strong> implementations</li><li>iosMain stores iOS-specific parts, including <strong>actual</strong> implementations</li></ul><p>Each source set has its own dependencies. Kotlin standard library is added automatically to all source sets, you don’t need to declare it in the build script.</p><h4><strong>expect/</strong><strong>actual</strong></h4><p><strong>expect</strong> defines an expected declaration<em> (</em>It’s used inside the <em>commonMain), </em>and platform source sets must provide the <strong>actual </strong>specific implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzQbBprgr6atQguG5RjaTw.png" /></figure><pre>// Common<br><strong>expect</strong> class Platform() {<br>    val platform: String<br>}</pre><p>It expects the targets to provide platform-specific implementations for <em>Platform</em>, and the common code can now use this declaration without any consideration of how it is implemented.</p><pre>//Android<br><strong>actual</strong> class Platform actual constructor() {<br>    actual val platform: String = &quot;Android ${android.os.Build.VERSION.<em>SDK_INT</em>}&quot;<br>}</pre><pre>//iOS<br>import platform.UIKit.UIDevice</pre><pre><strong>actual</strong> class Platform actual constructor() {<br>    actual val platform: String = UIDevice.currentDevice.systemName() + &quot; &quot; + UIDevice.currentDevice.systemVersion<br>}</pre><h4>Run your application on Android</h4><p>In the list of run configurations, select <strong>androidApp</strong> and then click <strong>Run</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*xO6cLCspvXMPgtibQGt2eA.png" /><figcaption>configurations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESbtl9_hCxwroJwlv5TMow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rD3O7LrqDR6fK5R1e1GuEw.gif" /><figcaption>run successfully</figcaption></figure><h4>Run your application on iOS</h4><p>In the list of run configurations, select <strong>iosApp</strong> and then click <strong>Run</strong>.</p><p>If you want to run your application on another simulated device, you can add a new run configuration by clicking on <strong>Edit Configurations</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1cLktRU8HILgv6nPps0KQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M61q4-8wDkrTWy0fbKJKDQ.png" /><figcaption>iOS simulator</figcaption></figure><p>Here is github sample code that you can checkout:</p><p><a href="https://github.com/alanrb/Kotlin-Multiplatform/tree/part1">https://github.com/alanrb/Kotlin-Multiplatform/tree/part1</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eed52ae443b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android MasterKeys deprecated — Migrate to EncryptedSharedPreferences]]></title>
            <link>https://alanrb.medium.com/android-masterkeys-deprecated-migrate-to-encryptedsharedpreferences-4f99d68ff186?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f99d68ff186</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 03:25:28 GMT</pubDate>
            <atom:updated>2021-02-19T03:10:18.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android MasterKeys deprecated — Migrate to EncryptedSharedPreferences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOXE4NbmCQPcCLiYrxrHDg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chrispanas?utm_source=medium&amp;utm_medium=referral">Chris Panas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If your application needs to save key-value pairs — such as API keys — <a href="https://developer.android.com/jetpack">Android Jetpack</a> provides the <a href="https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences">EncryptedSharedPreferences</a> class, which uses the same SharedPreferences interface that you’re used to.</p><h3>Setup</h3><p>To get started with the security library, add the following dependency:</p><pre>dependencies <strong>{</strong><br>    implementation &#39;androidx.security:security-crypto:1.1.0-alpha03&#39;<br><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ocuu1Qai0u3xSjt-Uu2ZaA.png" /></figure><p>But after upgraded to <a href="https://developer.android.com/jetpack/androidx/releases/security#security-crypto-1.1.0-alpha01">1.1.0-alpha01</a>, MasterKeys is deprecated:</p><pre>New MasterKey class provides more options for keys, also deprecating MasterKeys to support new features and versions of Android that do not have KeyGenParamSpec.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjwFOPzTXmzj4uZB8IQxxQ.png" /></figure><p>We need to use <a href="https://developer.android.com/reference/androidx/security/crypto/MasterKey.Builder"><em>MasterKey.Builder</em></a><em> instead. To create MasterKey:</em></p><pre>companion object {<br>    const val MASTER_KEY_ALIAS = &quot;yourKeyAlias&quot;<br>    const val KEY_SIZE = 256<br>}</pre><pre>private val keyGenParameterSpec = KeyGenParameterSpec.Builder(<br>    MASTER_KEY_ALIAS,<br>    KeyProperties.<em>PURPOSE_ENCRYPT </em>or KeyProperties.<em>PURPOSE_DECRYPT<br></em>).setBlockModes(KeyProperties.<em>BLOCK_MODE_GCM</em>)<br>    .setEncryptionPaddings(KeyProperties.<em>ENCRYPTION_PADDING_NONE</em>)<br>    .setKeySize(KEY_SIZE)<br>    .build()<br><br>private val masterKeyAlias = MasterKey.Builder(context, MASTER_KEY_ALIAS)<br>    .setKeyGenParameterSpec(keyGenParameterSpec)<br>    .build()<br><br>private val preferences = EncryptedSharedPreferences.create(<br>    context,<br>    context.getString(R.string.<em>preference_file_key</em>),<br>    masterKeyAlias,<br>    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,<br>    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM<br>)</pre><p>For some device, the error appears on creating EncryptedSharedPreferences (<strong>1.1.0-alpha03</strong>)</p><pre>Caused by: com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException: <br>  at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parsePartialFrom (GeneratedMessageLite.java:1566)<br>  at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parseFrom (GeneratedMessageLite.java:1664)<br>  at com.google.crypto.tink.proto.Keyset.parseFrom (Keyset.java:957)<br>  at com.google.crypto.tink.integration.android.SharedPrefKeysetReader.read (SharedPrefKeysetReader.java:84)<br>  at com.google.crypto.tink.CleartextKeysetHandle.read (CleartextKeysetHandle.java:58)<br>  at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.read (AndroidKeysetManager.java:328)<br>  at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewKeyset (AndroidKeysetManager.java:287)<br>  at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build (AndroidKeysetManager.java:238)<br>  at androidx.security.crypto.EncryptedSharedPreferences.create (EncryptedSharedPreferences.java:155)<br>  at androidx.security.crypto.EncryptedSharedPreferences.create (EncryptedSharedPreferences.java:120)</pre><p>Because after uninstalling the application you still have backed up your crypto file which you definitely can’t decrypt after installing a new version.</p><blockquote>You can disable backups by setting android:allowBackup to false:</blockquote><pre>&lt;manifest ... &gt;<br>    ...<br>    &lt;application <br>        android:allowBackup=&quot;false&quot;<br>        android:fullBackupContent=&quot;false&quot;&gt;<br>        ...<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><blockquote>Exclude specific shared preferences</blockquote><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;full-backup-content&gt;<br>    &lt;exclude domain=&quot;sharedpref&quot; path=&quot;.&quot;/&gt;<br>&lt;/full-backup-content&gt;</pre><p><a href="https://developer.android.com/guide/topics/data/autobackup#IncludingFiles">https://developer.android.com/guide/topics/data/autobackup#IncludingFiles</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f99d68ff186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing ConcatAdapter In Android]]></title>
            <link>https://alanrb.medium.com/implementing-concatadapter-in-android-c18f275eeb51?source=rss-49b08bc0b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/c18f275eeb51</guid>
            <category><![CDATA[mergeadapter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[alanrb]]></dc:creator>
            <pubDate>Thu, 25 Jun 2020 09:11:41 GMT</pubDate>
            <atom:updated>2020-06-25T09:11:41.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*fN26vQXZgL57hRyL-n4l2g.png" /></figure><h3>TL;DR</h3><p>Let’s say the designer team give you a design as above screenshot. The first idea is using RecyclerView with multiple view types inside, but it will be a lot of view types that you need to manage.</p><p>Sine <a href="https://developer.android.com/jetpack/androidx/releases/recyclerview#recyclerview-1.2.0-alpha04">recyclerview:1.2.0-alpha04</a>, <strong>ConcatAdapter</strong> is introduced that presents the contents of multiple adapters in sequence.</p><h3>Integration</h3><p>Add the dependencies for the artifacts you need in the build.gradle file for your app or module:</p><pre>dependencies <strong>{<br></strong>    implementation &quot;androidx.recyclerview:recyclerview:1.2.0-alpha04&quot;<br><strong>}</strong></pre><p>For example, we need to show a header layout as user info, a note, then a list of photos. We will create three different adapters:</p><pre>HeaderAdapter<br>NoteAdapter<br>GalleryAdapter</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gu1ZxZ35yAy-HSUSGGWjRw.png" /></figure><p>We can merge these three adapters by using constructor or just add one by one:</p><pre>val concatAdapter = ConcatAdapter()<br>concatAdapter.addAdapter(characterAdapter)<br>concatAdapter.addAdapter(noteAdapter)<br>concatAdapter.addAdapter(galleryAdapter)</pre><pre><em>with</em>(<strong>rvData</strong>) <strong>{<br>    </strong><em>adapter </em>= concatAdapter<br><strong>}</strong></pre><p>In main layout, we will add a recyclerView:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;FrameLayout 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:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/<strong>rvData</strong>&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        app:layoutManager=&quot;androidx.recyclerview.widget.LinearLayoutManager&quot; /&gt;<br><br>&lt;/FrameLayout&gt;</pre><h3><strong>Keynote</strong></h3><ol><li>By default, each added adapter will have its own isolated pool of <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder">RecyclerView.ViewHolder</a>s, with no re-use in between added adapters.</li></ol><p>If your <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter">RecyclerView.Adapter</a>s share the same view types, and can support sharing <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder">RecyclerView.ViewHolder</a> s between added adapters, provide a config like this:</p><pre>val config = ConcatAdapter.Config.Builder().setIsolateViewTypes(true)<br>    .build()<br>val concatAdapter = ConcatAdapter(config)</pre><p>2. We can remove an adapter by:</p><pre>concatAdapter.removeAdapter(noteAdapter)</pre><h3>Conclusion</h3><p>It’s an alpha version of development, there may be changed or removed in next version, so consider to use.</p><p>You can find the sample code <a href="https://github.com/alanrb/Android-ConcatAdapter">here</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c18f275eeb51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>