<?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 Miki Mendelson on Medium]]></title>
        <description><![CDATA[Stories by Miki Mendelson on Medium]]></description>
        <link>https://medium.com/@mikimints?source=rss-ed3c91e2ac7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G69-mWEIS6ayCQli6KqPUA.jpeg</url>
            <title>Stories by Miki Mendelson on Medium</title>
            <link>https://medium.com/@mikimints?source=rss-ed3c91e2ac7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:44:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikimints/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[DroidUVC: A new Android SDK for UVC cameras]]></title>
            <link>https://blog.devgenius.io/droiduvc-a-new-android-sdk-for-uvc-cameras-364b85bad5ae?source=rss-ed3c91e2ac7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/364b85bad5ae</guid>
            <category><![CDATA[usb]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[cameras]]></category>
            <dc:creator><![CDATA[Miki Mendelson]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 04:35:15 GMT</pubDate>
            <atom:updated>2026-10-19T07:39:38.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJzrFuw05JwlI77B" /><figcaption>Photo by <a href="https://unsplash.com/@nhuenerfuerst?utm_source=medium&amp;utm_medium=referral">Nils Huenerfuerst</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today, I am happy to welcome my new DroidUVC project — A modern SDK for working with UVC cameras on Android, built on top of libuvc and Jetpack Compose.</p><p>This library was heavily inspired by the old <a href="https://github.com/saki4510t/UVCCamera">UVCCamera</a> project, but it brings in a more modern approach, with better support, testing, maintenance and ecosystem integration.</p><figure><img alt="Bugdroid holding a pink polaroid camera, taking a picture of another Bugdroid. This is the main logo of the Android Polaroid project" src="https://cdn-images-1.medium.com/max/432/1*4VdWV5dwWHIbXpqOr5m24w.png" /><figcaption>DroidUVC Logo</figcaption></figure><p>Installing is available through Maven:</p><pre>dependencies {<br>   implementation(&quot;io.github.mikimn:droiduvc-compose:0.2.1&quot;)<br>}</pre><p>And usage is as easily as it gets:</p><pre>@Composable<br>fun CameraScreen() {<br>    val devices by rememberUvcDevices()                         // updates on plug / unplug<br>    val device = devices.firstOrNull() ?: return Text(&quot;Connect a UVC camera&quot;)<br>    val permission = rememberUsbPermission(device)              // CAMERA + per-device USB permission<br>    if (!permission.granted) {<br>        Button(onClick = permission.request) { Text(&quot;Allow camera access&quot;) }<br>        return<br>    }<br>    if (!rememberIsStarted()) return                            // release the camera in the background<br>    when (val state = rememberUvcCamera(device)) {              // opens off the main thread, closes on dispose<br>        UvcCameraState.Opening -&gt; Text(&quot;Opening…&quot;)<br>        is UvcCameraState.Failed -&gt; Text(state.message)<br>        is UvcCameraState.Ready -&gt; UvcCameraPreview(state.camera, Modifier.fillMaxWidth())<br>    }<br>}</pre><p>Want to know more? Want to contribute to the project? Visit the documentation here: <a href="https://mikimn.github.io/droiduvc/">https://mikimn.github.io/droiduvc/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364b85bad5ae" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/droiduvc-a-new-android-sdk-for-uvc-cameras-364b85bad5ae">DroidUVC: A new Android SDK for UVC cameras</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse-engineering My Smart Switch for Fun and Profit]]></title>
            <link>https://blog.devgenius.io/reverse-engineering-and-reviving-a-non-functional-smart-power-switch-aa878699bf30?source=rss-ed3c91e2ac7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa878699bf30</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Miki Mendelson]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 17:58:57 GMT</pubDate>
            <atom:updated>2026-06-23T08:40:57.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reverse-engineering and Reviving a Non-functional Smart Power Switch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LxTMmuP9-jd2oP_" /><figcaption>Photo by <a href="https://unsplash.com/@zanilic?utm_source=medium&amp;utm_medium=referral">Zan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently came across a problem that sparked my interest. In my house, we have a <a href="https://www.electrosen.co.il/product/er-smart-switch-%D7%9E%D7%A4%D7%A1%D7%A7-%D7%9C%D7%93%D7%95%D7%93-%D7%97%D7%A9%D7%9E%D7%9C%D7%99-%D7%9C%D7%A7%D7%95%D7%A4%D7%A1%D7%90-%D7%9E%D7%9C%D7%91%D7%A0%D7%99%D7%AA-3-%D7%9E%D7%A7%D7%95%D7%9E/">local-brand</a> smart switch installed as the switch for our boiler. It works something like this: First, I download a dedicated app for my Android/iOS device. When I first turn on the switch (by lifting the fuse switch associated with it), it opens a WiFi access point (AP) with an indicative name to its brand. I then connect to the endpoint and open the app on my phone, which proceeds to automatically discover the device. I can then configure some parameters for it, and select my home network. When I do, my phone disconnects from the AP, and connects back to my home network. Soon after, the AP disappears and the switch’s AP indicator light stops flickering. From that point on, the switch appears in the app, and I can access it from any network (even when not connected to my home router) and manage it:</p><ul><li>Toggle the switch on/off</li><li>Set a time of day for which the switch will turn on and off (A kind of simple scheduler), which is very useful for automatically pre-heating water in the boiler (for example, for taking a nice morning shower).</li><li>Control several preferences of the switch, most notably whether it makes a sound whenever it is switched, or not.</li></ul><p>Well, one day, the device stopped working ☹️. I could still reset it and manage it locally (when I was connected to my home network) but I could no longer access it when I was outside my house. This went on for a while, and while I was wondering whether to just buy a new one, I was also determined to make it work on my on (because why spend money when you have an allegedly working piece of hardware, right?)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Pxcsid28UpfX3m9O8I4M5g.jpeg" /><figcaption>The smart switch (Credit: Electrosen Inc.)</figcaption></figure><p>It also didn’t help that the official application seemed to have been removed from the Play Store (on Android).</p><p>And so, I set my goal to obtain the same functionalities that my smart switch previously had: The ability to setup, connect, and manage it seamlessly.</p><h3>Part 1: Communication is Key</h3><p>The first step in winning back my smart home experience, is to understand how this quirky piece of hardware works. As I wrote earlier, this is a local brand from a company that seems to have been closed in the past year or so. It also sported its own dedicated, far-from-perfect application, which is no longer available to download by any official means (but we’ll get to that soon.)</p><p>With all of this in mind, my intention was to analyze the inner workings of the switch without assuming access to its physical form factor or to its source code (Which I don’t possess.) From my first description of how the device works, I laid down these assumptions (which are yet to be confirmed):</p><ul><li>The device contains a bi-directional WiFi module which can act as both a client (to connect to a network) and and AP (to host a connection)</li><li>Since I can control the switch outside my house, I assume the device is aware of some sort of server available on the internet, from which it can receive commands as a sort of proxy to the application. The existence (or non-existence) of such a server may explain why this feature suddenly stopped working one day.</li><li>The device connects to my home network to access the internet, which is why I selected it when first setting up the device. This is common when setting up IoT devices like this smart switch.</li></ul><p>Since, as I said, the APK is not available on the Play Store anymore, I had to come up with a different solution. There are several sites that automatically scan and index APKs for sideloading different versions of the APK, for example <a href="https://m.apkpure.com/wifi-er/com.WiFiER.activity">here</a>.</p><p><strong>Disclaimer: </strong>This is a dangerous step, and sideloading apps from unknown sources generally means that they are subject to less strict security checks and can be infected with malware. You can read more about it <a href="https://www.avg.com/en/signal/is-apkpure-safe">here</a>. I am doing it at my own risk, and you should consider twice before doing it yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*f3bP-7oVFXsKdqE2i3pnNQ.png" /><figcaption>Downloading the app from an alternate side-loading app store.</figcaption></figure><p>Noting the developr name, I assume the development of this app was outsourced and not done in-house. The first step is to look at how the switch communicates with the phone. There are a number of ways to do this:</p><ul><li>tcpdump or similar tools: would require rooting my phone.</li><li>VPN based solutions: Android apps are able to capture application traffic by installing a VPN service that only writes that traffic to a capture file. I found <a href="https://play.google.com/store/apps/details?id=app.greyshirts.sslcapture">Packet Capture</a> and <a href="https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture">tPacketCapture</a> to be decent solutions, although they sometimes block the traffic from reaching the application which can cause sessions to disconnect.</li></ul><p>I decided to go with Packet Capture. I sideloaded and opened the WiFi ER app on my phone while being connected to the dedicated AP. The app immediately discovered the device and suggested adding it to the device list.</p><p>First, I immediately noticed the device sending some short UDP packets to port 50000, and receiving some longer packets back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Rxmse-k_7IAS-UVyFXJ3Hw.jpeg" /><figcaption>Using Packet Capture as middleware so sniff bi-directional traffic to the application.</figcaption></figure><p>I decided to write a short Python script to try this out myself:</p><pre>import socket<br><br>UDP_IP = &quot;192.168.1.1&quot;  # Device&#39;s local home IP<br>UDP_PORT = 50000<br><br># UDP Socket<br>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<br><br>def sendAndReceive(data):<br>    if type(data) == str:<br>        data = bytes(data, &quot;UTF-8&quot;)<br>    sock.sendto(data, (UDP_IP, UDP_PORT))<br><br>    res, addr = sock.recvfrom(1024)<br>    print(&quot;Response from {}:{}&quot;.format(*addr))<br>    return res<br><br>res = sendAndReceive(&quot;\x01\x75\x00\x01\x77&quot;)<br>print(res)</pre><p>I tested this out by disconnecting my phone, and connecting my computer to the AP, and it seemed to work!</p><pre>Response from 192.168.1.1:50000<br>b&quot;\x06a81b6a7994e9r&#39;\x01\x0b\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x27\x11\x0c47.88.79.171\x00\x9f&quot;</pre><p>Looking at the response, it seems to contain some printable string at the beginning, a bunch of unknown bytes, and what seemed to be an IP address at the end. This could be perhaps the address of the server that the device connects to, in order to receive commands over the internet.</p><p>I sniffed the traffic using Wireshark while connected to the AP with my computer. We can observe that the string at the beginning is exactly the MAC address of the device’s network card:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*5jPRIeNsjsAlfwptpDot6A.png" /></figure><p>There also seems to be an IP address at the end of the response: 47.88.79.171. My initial guess is that this might be the aformentioned server with which the switch can communicate to receive commands from the app outside the home network. Looking up this IP address, it seems to belong to a range of addresses associated with Alibaba Cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCJcBYzi1j80P7zV_wy80A.png" /><figcaption>WHOIS information on the suspected IP address (Credit: <a href="https://ipinfo.io/">https://ipinfo.io/</a>)</figcaption></figure><p>Unfortunately, the IP itself does not answer pings, which may indicate that this server is down. Ok, so by now we’ve realized that the device somehow knows when to connect to a server that allows communication outside the house, and we understand roughly how this flow looks like in the app. Since I aim to have just the basic functionality, I still need to understand how the device receives on/off commands. For that, I sniffed the app connection again, while pressing the on/off buttons on my phone.</p><p>The packets look like this (left — switch on; right — switch off):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PweZLwWeDRZ4oTwqoWMqaA.jpeg" /></figure><p>It seems as if the 5th byte determines whether the switch is on or off in this configuration, and there also seems to be a 5-byte addendum, as in the first message, but this time there is an extra bit at the end that seems to change sometimes, and 4 bits at the beginning that look quite similar in all configurations (on the right, the 4th byte seems to increase by one with each message sent). With this in mind, I can support turning the switch on and off without the application!</p><p>I think this is enough understanding of the communication protocol, and we can take a deeper look at how it is implemented under the hood.</p><h3>Part 2: Playing with Code</h3><p>We now have a basic sense of how the protocol looks between the switch and its controller (be it the Android device or a command server):</p><ul><li>The switch has a UDP socket open on port 50000, and it listens to requests.</li><li>The controller sends requests that contain some data and probably some opcode for the message type, and the device responds. Right now we successfully sent three such messages: call them HELLO, SWITCH_ON and SWITCH_OFF.</li></ul><p>This still leaves some unanswered questions that require a deeper understanding of this protocol:</p><ul><li>How does the device communicate outside the LAN? If it sits behind a NAT-ed router and has a known open port, it somehow has to initiate a connection to the server (which is outside the LAN) and employ a form of <a href="https://en.wikipedia.org/wiki/UDP_hole_punching">UDP hole punching</a>.</li><li>How does the communication protocol look at a higher level? What other message types exist? Can we forge requests ourselves without the need to replay packets?</li></ul><p>To answer these questions, I decided to decompile and look at the application code. To do so, I used a simple online <a href="http://www.javadecompilers.com/apk">JADX decompiler for Android</a>. The code was mostly in tact, with a lot of the files, classes and variable names ending up obfuscated, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*oCGPAVe6C4fXMT1o1vAV8Q.png" /></figure><p>Since I knew that the device communicates over a UDP socket in port 50000, I anchored my search to the send() and receive() methods of the Java <a href="https://docs.oracle.com/javase/7/docs/api/java/net/DatagramSocket.html">DatagramSocket</a> class. I also looked for the constant port number in code. I quickly discovered that there is a pretty consistent format for sending commands over to the switch:</p><ul><li>The first byte’s function wasn’t quite clear to me yet, because all code examples I could find in the app passed the constant 1 to it. I assumed this is the protocol version, which is not uncommon in such datagram protocol</li><li>The second byte is an opcode for the message. For example, 0x75 for HELLO and 0x1 for SWITCH_ON and SWITCH_OFF (And I suspect for other methods that control the hardware as well, so we shall call these DEVICE_CONTROL going forward.)</li><li>The third byte length is the message data length (excluding header bytes).</li><li>The fourth byte is a generated ID for the message, which is cycled through 256 values.</li><li>Then, the message data is laid out for length bytes.</li><li>The last byte (after the data) is a sum of all other message bytes (including headers), modulu 255—a sort of simple checksum mechanism for the message.</li></ul><p>OK, so far so good, and we can test this by writing a simple wrapper for sending messages:</p><pre>def sendAndReceive(data, receive=True):<br>    if type(data) == str:<br>        data = bytes(data, &quot;UTF-8&quot;)<br>    sock.sendto(data, (UDP_IP, UDP_PORT))<br><br>    if receive:<br>        res, addr = sock.recvfrom(1024)<br>        print(&quot;Response from {}:{}&quot;.format(*addr))<br>        return res<br><br><br>def calculateLastByte(opcode, pid, data=None, version=1):<br>    length = len(data) if data else 0<br>    checksum = version + opcode + pid + length + sum(data)<br>    return (checksum &amp; 0xff), length<br><br><br>def sendMessage(opcode, data=None, version=1, receive=True):<br>    global packet_id<br>    if isinstance(opcode, Enum):<br>        opcode = opcode.value<br>    if not data:<br>        data = &quot;&quot;<br>    <br>    if type(data) != bytes:<br>        data = bytes(data, &quot;UTF-8&quot;)<br>    <br>    last_byte, length = calculateLastByte(opcode, packet_id, data=data, version=version)<br>    wrapped_data = struct.pack(&quot;!bBbb%dsB&quot; % length, version, opcode, length, packet_id, data, last_byte)<br>    res = sendAndReceive(wrapped_data, receive=receive)<br>    packet_id += 1<br>    packet_id %= 255<br>    return res</pre><p>Now, I could define some basic messages, based on the packets I captured earlier, and on dissecting the communication protocol itself from the code:</p><pre>class MessageType(Enum):<br>    DEVICE_CONTROL = 0x01<br>    UPDATE_GATEWAY = 0x70<br>    HELLO_EMPTY = 0x75<br>    HELLO_WITH_MAC = 0x76<br>    UPDATE_SERVER = 0xc1</pre><p>The UPDATE_GATEWAY message is the one responsible for telling the device how to connect to the home network, so it may communicate its messages outside:</p><pre># Update gateway<br>ssid = b&quot;**********&quot;<br>password = b&quot;**********&quot;<br><br># Data format: <br>#   [magic], [magic], len(ssid), ssid, len(password), password<br>data = struct.pack(&quot;!bbb{}sb{}s&quot;.format(len(ssid), len(password)), 1, 2, len(ssid), ssid, len(password), password)<br>sendMessage(MessageType.UPDATE_GATEWAY, data=data, receive=False)</pre><p>I also realized the data relevant to turning the switch on and off, using the DEVICE_CONTROL message. Examples:</p><pre># Switch on<br>SWITCH_ON_MAP = [1, 0, 0, 0, 0, 0, 0, 1, 0, 0]<br>SWITCH_ON_DATA = struct.pack(&quot;!10b&quot;, *SWITCH_ON_MAP)<br>sendMessage(MessageType.DEVICE_CONTROL, data=SWITCH_ON_DATA, receive=False)<br><br># Switch off<br>SWITCH_OFF_MAP = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]<br>SWITCH_OFF_DATA = struct.pack(&quot;!10b&quot;, *SWITCH_OFF_MAP)<br>sendMessage(MessageType.DEVICE_CONTROL, data=SWITCH_OFF_DATA, receive=False)</pre><p>I also found that the UPDATE_SERVER message is able to update the hardcoded server IP which we say earlier, so an arbitrary IPv4 address like so:</p><pre># My computer&#39;s private IP address on the home network<br>server_address = b&quot;192.168.1.21&quot;<br>port = 60000<br>request_code = 15<br><br>data = struct.pack(&quot;!Hb{}s&quot;.format(len(server_address)), (port - 40000), request_code, server_address) <br>sendMessage(MessageType.UPDATE_SERVER, data=data, receive=False)</pre><p>Again, the magics here are not so important to understand, so long as we get this setup to work. And indeed, after sending the UPDATE_GATEWAY and UPDATE_SERVER messages to the device, its network indicator led suddenly stopped flickering, and the device’s AP disappeared. I connected to my home network (The one I supplied to the device as well) and began sniffing UDP packets. This is what I saw:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mFJF7jGDEdyzZ4wDL5esQ.png" /></figure><p>Great, it seems as if the device attempts to reach my computer as its server, with its own hello packet that seems to contain the same device identifier that’s just its MAC address, as well as an 8-byte password that is used in the app to connect to it remotely. I found out that the password is also editable, along with some more device parameters, with a different message type like so:</p><pre># Edit device<br>device_address = 0<br>open_search = True<br>open_remote_control = True<br>new_password = b&quot;Test1234&quot;<br>new_password += b&quot;\0&quot; * (8 - len(new_password))<br>open_dev_params = (0, 0, 0)<br>img_idx = 0<br>channel_info = 0<br>name = b&quot;Switch1&quot;<br><br>FORMAT_EDIT_DEVICE = &quot;!Hbb8sbbbbbxxb{}s&quot;.format(len(name))<br>data = struct.pack(FORMAT_EDIT_DEVICE, device_address, open_search, open_remote_control, new_password, *open_dev_params, img_idx, channel_info, len(name), name)<br>sendMessage(MessageType.EDIT_DEVICE, data=data)</pre><p>Ok, great. Let’s recap what we managed to do by now on the local network:</p><ul><li>Point the device to a different server</li><li>Make it connect to the home network and start pinging the server with hello messages</li><li>Control the switch with DEVICE_CONTROL messages to turn it on and off.</li></ul><p>This is still only true to the <strong>local network</strong>, since we are sending those messages to the device on a known port 50000. We do, however, see that the device initiates a connection to its configured server. If we figure out how to send the same control messages over on this connection, we can setup a server outside the LAN to receive those message and maintain a connection to the device, which we can then control outside the house!</p><h3>Part 3: Into the Internet and Beyond!</h3><p>We are still left with the part that is probably most interesting: Controlling the device from outside the local network. This becomes problematic due to <a href="https://www.geeksforgeeks.org/network-address-translation-nat/">Network Address Translation (NAT)</a>. This means that a server outside my home network does not see my real IP address and therefore cannot directly communicate with me. A common solution is to make the switch first connect to the server, and send data over this connection, while maintaining the NAT entry in the router, thus allowing for bi-directional communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*pVXdFpMpc4Mmx9npKTlcNQ.png" /></figure><p>I suspect that this is what happens here, and also why the switch immediately begins sending packets to the address we configured using the UPDATE_SERVER message. The problem is, so far I’ve controlled the device by sending packets directly to its known open port 50000. Since this is no longer possible when behind a NAT, I’d like to figure out how the server relays this information over the bidirectional connection that is maintained by the device itself.</p><p>This is the part that’s more tricky, because we neither have access to the server itself (it’s down) nor do we have access to its code or functionality. This may mean that it employs a different protocol to communicate with the switch. We can try a few different blackbox approaches to this:</p><ul><li>Assume that the server is a pure relay (is sends everything it receives from the app to the switch, kind of like a reverse SSH server), and try to mimic this behavior.</li><li>Try to find some wrapper logic in the application code that points to how the server receives command packets from the device.</li></ul><p>The first approach is easy to test. I refactored my code a bit so that it acts as a Python server. When it receives the first packet from the device, it decodes it and sends back a DEVICE_CONTROL message in the same way as before:</p><pre>data, (device_ip, device_port) = sock.recvfrom(RECV_MAX_SIZE)<br>dataPrefix = &quot;!B12s8sB&quot;<br>dataPrefixLen = struct.calcsize(dataPrefix)<br><br>(opcode, mac, password, dataLength), data = struct.unpack(<br>    dataPrefix, data[:dataPrefixLen]<br>), data[dataPrefixLen:]<br><br>mac = mac.decode(&quot;utf-8&quot;)<br><br>dataSuffix = &quot;{}sBB&quot;.format(dataLength)<br><br>(data, packetId, lastByte) = struct.unpack(dataSuffix, data)<br><br>if opcode == 9:<br>    logging.info(&quot;Connection from {}:{}&quot;.format(<br>        device_ip, device_port<br>    ))<br>    logging.info(&quot;\tmac = %s&quot;, mac)<br>    logging.info(&quot;\tpassword = %s&quot;, password)<br>    logging.info(&quot;\tdataLength = %d&quot;, dataLength)<br>    logging.info(&quot;\tpacketId = %d&quot;, packetId)<br>    logging.info(&quot;\tchecksum = %x&quot;, lastByte)<br>    logging.info(&quot;\tdata = %s&quot;, data)<br>    # ... Send SWITCH_ON message</pre><p>Here, I figured out that the first packet always contains the 12-byte MAC address (in string form), followed by the 8-byte password, and a checksum. The first byte is always 9 (presumably an opcode for this specific message).</p><p>Unfortunately, this didn’t work. I played a bit with the parameters but nothing seemed to trigger the switch the way I wanted.</p><p>Next up, I followed with my other approach. It makes sense that the app would authenticate itself using the MAC address and the password, since this (kind of) prevents unauthorized access the users outside my home network. I looked at the code a bit and stumbled upon this function (after manually renaming some of the obfuscated variable names):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txsWhGZLq22iTQ_ZhYYXag.png" /></figure><p>It is used in one main place, which was a bytecode function the could not be decompiled due to missing symbols:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53J65Cdu5akW_zhGLomaRg.png" /></figure><p>I was able to trace back some of the variable names and figured out that the data passed to the DeviceRemotePacket is simple a packet that would otherwise be sent directly to the device on port 50000! This means that this class acts as a wrapper for the original messages. If the server was just relaying this information to the switch, I should be able to mimic this behavior. For that, I’ve added the wrapper code to my simple server:</p><pre># ... Send SWITCH_ON message<br><br>SWITCH_ON_MAP = [1, 0, 0, 0, 0, 0, 0, 1, 0, 0]<br>SWITCH_OFF_MAP = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]<br>SWITCH_ON_DATA = struct.pack(&quot;!10b&quot;,<br>                             *SWITCH_ON_MAP)<br>SWITCH_OFF_DATA = struct.pack(&quot;!10b&quot;,<br>                              *SWITCH_OFF_MAP)<br><br>messenger.send_remote_message(<br>    device_ip,<br>    device_port,<br>    MessageType.DEVICE_CONTROL,<br>    mac,<br>    &quot;Test1234&quot;,<br>    data=SWITCH_ON_DATA<br>)<br><br>from time import sleep<br>sleep(2)<br><br>messenger.send_remote_message(<br>    device_ip,<br>    device_port,<br>    MessageType.DEVICE_CONTROL,<br>    mac,<br>    &quot;Test1234&quot;,<br>    data=SWITCH_OFF_DATA<br>)</pre><pre>class MessageSocket:<br>    _VERSION = 1<br>    _MESSAGE_STRUCT = &quot;!BBBB{}sB&quot;<br>    _REMOTE_MESSAGE_STRUCT = &quot;!B12s8sBB{}sB&quot;<br><br>    def __init__(self, socket):<br>        self._socket = socket<br>        self._packet_id = 0<br><br>   # ... More functions here ...<br><br>    def _build_message(self, opcode: int, data: bytes):<br>        version = self._VERSION<br>        last_byte, length = self._calculate_last_byte(<br>            opcode, self._packet_id, data=data, version=version<br>        )<br>        return struct.pack(<br>            self._MESSAGE_STRUCT.format(length), version, opcode, length,<br>            self._packet_id, data, last_byte<br>        )<br><br>    def send_remote_message(self, address: str, port: int,<br>                            opcode: MessageType, mac: str, password: str,<br>                            data: str = None):<br>        opcode = opcode.value<br>        data = self._sanitize_str(&quot;&quot; if not data else data)<br>        mac = self._sanitize_str(mac)<br>        password = self._sanitize_str(password)<br><br>        wrapped_data = self._build_message(opcode, data)<br>        wrapped_len = len(wrapped_data)<br>        wrapped_opcode = 5<br>        checksum = self._byte_checksum(<br>            wrapped_opcode, wrapped_len, wrapped_data,<br>            self._packet_id, mac, password<br>        )<br><br>        wrapped_data = struct.pack(<br>            self._REMOTE_MESSAGE_STRUCT.format(wrapped_len),<br>            5, mac, password, wrapped_len, self._packet_id,<br>            wrapped_data, checksum<br>        )<br><br>        logger.debug(&quot;Remote message: {}&quot;.format(wrapped_data))<br>        res = self._send_and_receive(address, port, wrapped_data,<br>                                     receive=False)<br>        self._increment_packet_id()<br>        return res</pre><p>And just like that, it worked! The device sent a packet to the server, and then switched on and off after 2 seconds!</p><p>We’ve now completed a full writeup of the device’s capabilities, and all is left is to clean up the code, deploy the server code with a public IP, and write a simple client that will communicate with the server.</p><p>I’ve started from scratch with a device that was seemingly not working. With some blackbox testing and a bit of code reverse-engineering, I was able to revive the device! With some proper infrastructure code, this could easily become a usable device once again 😃.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa878699bf30" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/reverse-engineering-and-reviving-a-non-functional-smart-power-switch-aa878699bf30">Reverse-engineering My Smart Switch for Fun and Profit</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging in Java & Kotlin — Hidden Stack Overflows in the JVM]]></title>
            <link>https://blog.devgenius.io/advanced-debugging-for-java-kotlin-part-1-hidden-stacks-overflowing-3cf070bca8b0?source=rss-ed3c91e2ac7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf070bca8b0</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[bugs]]></category>
            <dc:creator><![CDATA[Miki Mendelson]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 13:23:12 GMT</pubDate>
            <atom:updated>2025-09-12T13:09:53.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vAwrh-3hKsEs15p_" /><figcaption>Photo by <a href="https://unsplash.com/@timothycdykes?utm_source=medium&amp;utm_medium=referral">Timothy Dykes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We often come across common, or not-so common bugs in our code. Some are easier to debug and fix, and some require more creative or methodical practices to analyze.</p><p>In this series, I will discuss some of the more cryptic, rare and tough bugs, and also give tips and insights into how to properly avoid them when writing code, and how to effectively debug.</p><p>This first of the series discusses a real-world example that I came across as a freelance software engineer.</p><h3>Step 1: Diagnosis</h3><p>A client approached me with user complaints regarding the latest version of an app that seems to have malfunctioned. According to users, the application (which runs in the background, sometimes for hours) stop after ~20 minutes of normal use, requiring a manual restart each time.</p><p>In general, there could be two main reasons for an Android application to be killed:</p><ul><li>An unhandled exception in the application</li><li>A forced kill by the operating system</li></ul><p>Trying to reproduce a crash that only happens after 20 minutes of use may be painsteaking, but assuming it is deterministic, it could easily lead us to one of the aformentioned cases — If there is a stack trace when the app crashes, we can easily find the cause. If not, it means that the system decided for some reason to kill our software.</p><h4>Tip #1: Always tag release versions in Git when managing user-facing software</h4><p>This may seem straightforward, but it proves very effective in isolating issues in code. For large, corporate projects this is usually a given, but when projects are managed by a single developer, or a small group of junior developers, such steps in the development cycle tend to be forgotten.</p><p>I took note of the problematic version, as given to me by the client, and checked out the appropiate version tag in our Git repo:</p><pre>git checkout tags/x.y.z</pre><p>I then compiled the application in debug type and ran it while timing its total runtime. I also recorded all Logcat output on my computer to a logfile to more effectively trace the bug later:</p><pre>adb logcat &gt; test.log</pre><p>Remarakbly, after ~30 minutes of runtime, the application crashed! But alas, neither a JVM or a native stack trace could be found 😢.</p><h4>Tip #2 (For Android developers): Use Android Code Search to diagnose system logs</h4><p>We now know that we didn’t kill our own software. But unfortunately, that means the OS did. To understand why, it is important to be able to extract useful information from the system logs, which also why it’s always a good practice to save a log file whenever reproducing such bugs. Whenever I look at system logs, I always open a</p><p>Looking a bit at the logs, I was able to spot some weird logs around the time of the crash, most notably:</p><pre>1691  1887 W BroadcastQueue: Can&#39;t deliver broadcast to &lt;mypackage&gt; (pid 28930). Crashing it.<br>1691  1887 D ActivityManager: kill pid:28930 processName:&lt;mypackage&gt; reason:scheduleCrash for &#39;can&#39;t deliver broadcast&#39; failed<br>1691  1887 I ActivityManager: Killing 28930:&lt;mypackage&gt;/uXaYYY (adj 100): scheduleCrash for &#39;can&#39;t deliver broadcast&#39; failed<br>1691  1887 W BroadcastQueue: Failure sending broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }<br>1691  1887 W BroadcastQueue: android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died<br>1691  1887 W BroadcastQueue:  at android.os.BinderProxy.transactNative(Native Method)<br>1691  1887 W BroadcastQueue:  at android.os.BinderProxy.transact(BinderProxy.java:591)<br>1691  1887 W BroadcastQueue:  at android.app.IApplicationThread$Stub$Proxy.scheduleRegisteredReceiver(IApplicationThread.java:1781)<br>1691  1887 W BroadcastQueue:  at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:700)<br>1691  1887 W BroadcastQueue:  at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:1035)<br>1691  1887 W BroadcastQueue:  at com.android.server.am.BroadcastQueue.processNextBroadcastLocked(BroadcastQueue.java:1223)<br>1691  1887 W BroadcastQueue:  at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:1175)<br>1691  1887 W BroadcastQueue:  at com.android.server.am.BroadcastQueue$BroadcastHandler.handleMessage(BroadcastQueue.java:218)<br>1691  1887 W BroadcastQueue:  at android.os.Handler.dispatchMessage(Handler.java:106)<br>1691  1887 W BroadcastQueue:  at android.os.Looper.loop(Looper.java:233)<br>1691  1887 W BroadcastQueue:  at android.os.HandlerThread.run(HandlerThread.java:67)<br>1691  1887 W BroadcastQueue:  at com.android.server.ServiceThread.run(ServiceThread.java:44)</pre><p>My app does subscribe to the android.intent.action.BATTERY_CHANGED intent filter to receive battery status, and it seems that the OS tried to deliver such an update to the app, but failed (since it crashed). This doesn’t help us discover what is the cause to the crash, but if focuses the timeline.</p><p>Looking a bit before this log, we find some very interesting logs:</p><pre>I ActivityManager: Process &lt;mypackage&gt; (pid XXXXX) has died: vis FGS<br>I libprocessgroup: Successfully killed process cgroup uid YYYYY pid XXXXX in 0ms<br>W ActivityManagerServiceInjector: AMS will block &lt;mypackage&gt;(&lt;mypackage&gt;) autostart due to process is killed by lmk in low memory</pre><p>This is a big hint that our application is possibly killed because it ran out of memory! At this point it took over to <a href="https://cs.android.com/">https://cs.android.com/</a> and tried to find some useful insight about these logs [<a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java;l=3450?q=%22%20has%20died%22%20%22ActivityManager%22">1</a>]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R96cjEj8FRyQmDX9aabbLA.png" /></figure><p>It does seem like the app was killed due to running out of memory. Unfortunate, but we are (hopefully) getting closer to finding the bug.</p><h3>Step 2: <strong>Etiology</strong></h3><p>We now know how to diagnose the crash, but we still cannot explain it. Etiology is the study of causation and origination. We know that our app runs out of memory, but why?</p><h4>Tip #3: Use memory profiling to diagnose bottlenecks</h4><p>Memory profiling in JVM-based apps is a super effective method to diagnose such issues, because such profiles tend to be very accurate.</p><p>Android Studio comes bundles with the <a href="https://developer.android.com/studio/profile/capture-heap-dump">Android Profier</a> and IntelliJ also offer its own memory profiler for IntelliJ and Java/Kotlin based software.</p><p>From here, I ran the app with a profiler installed for 20 minutes and, as expected, the app crashed. This is roughly what the memory usage graph shows for the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8ObHYPsDtLuVjCNsYrh6w.jpeg" /><figcaption>Output of the Android Memory Profiler (Icons represent invocations of the GC)</figcaption></figure><p>We notice a very disturbing trend here. First, it seems that the application maxes out its allowed heap usage very quickly, and this usage stays high throughout the entire lifetime of the app. Why, then, is the app getting killed only after several minutes? Well, we can also see that the GC acts every few seconds, releasing some of the heap memory, causing slight spikes in the memory usage, and resulting in this tooth-like pattern.</p><p>The profiler also conveniently shows us the number of allocations and deallocations of JVM objects on the heap, and pinpoints the issue to one of my implementations using the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html">Executor</a> API.</p><p>At this point, looking at the problematic code for some time brought me to an understanding of the bug. To explain what I found, let’s reproduce a simple example of it in steps.</p><h4>Step 3: Prognosis</h4><p>Let’s now prove that we are able to fix this bug by reproducing a simple example of it. We’ll delve a bit into JVM internals while doing so.</p><p>Consider this example of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a3c770344b991c323f669a6add45b1b/href">https://medium.com/media/6a3c770344b991c323f669a6add45b1b/href</a></iframe><p>The code itself might not amount the much, but it’s pretty easy to see what will happen, and every developer having some basic experience with Java or Kotlin will recognize this as a stack overflow:</p><pre>Exception in thread &quot;main&quot; java.lang.StackOverflowError<br> at Case1StackOverflow.doSomething(Case1HiddenStackOverflow.kt:7)<br> at Case1StackOverflow.getAList(Case1HiddenStackOverflow.kt:12)<br> at Case1StackOverflow.doSomething(Case1HiddenStackOverflow.kt:7)<br> at Case1StackOverflow.getAList(Case1HiddenStackOverflow.kt:12)<br> at Case1StackOverflow.doSomething(Case1HiddenStackOverflow.kt:7)<br> at Case1StackOverflow.getAList(Case1HiddenStackOverflow.kt:12)<br> ...</pre><p>This is a JVM error, and it happens when the virtual runtime determined that it had exhausted its resources on the <strong>Call Stack</strong>, which has an upper boundary for the depth of recursion. Since most programs should never reach this depth, getting this error usually means uintended recursion. In our example, doSeomthing() is a seemingly boring function, but since it encapsulates a call to a Kotlin <a href="https://kotlinlang.org/docs/properties.html#getters-and-setters">Property’s getter</a>, it allow the recursive invocation of itself. This immediately leads us to another important tip:</p><h4>Tip #4: In Kotlin, be careful when calling <strong>member functions</strong> from the context of a property getter.</h4><p>This may seem like a stretch, but this type of code is extremely confusing, especially to developers coming from languages where property getters are not a thing. On a more high-level note, while this code is valid in Kotlin, in more complex flows it may violate an implicit assumption on properties — their getters could somehow change the inner state of the object, which may cause unwanted side-effects.</p><p>Ok, this is a good thing to remember, but we’re still not near reproducing our bug. Now, let’s consider adding an Executor to our code like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e9520326db4ab0098c763dc618f4dd/href">https://medium.com/media/c3e9520326db4ab0098c763dc618f4dd/href</a></iframe><p>We’ve wrapped our doSomething() implementation with a call to execute, which sends our code to be executed on a different thread (In this case, a snigle thread allocated using Executors.newSingleThreadExecutor()). You can run this code yourself and prove that in fact, now we are not getting a StackOverflowError, and our code runs <strong>indefinitely</strong>!</p><p>We can also inspect the profiler to look at how the heap memory behaves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*8JDHl21kD-MOPEml5-3ubg.png" /></figure><p>It seems like there is no memory usage spikes, but we’ve also eliminated the StackOverflowError, leaving a hanging thread to run forever. Yikes! This makes sense, because Executors maintain a queue of Runnable objects, effectively shifting the calling responsibility from the JVM’s Call Stack to an internal data structure. In our example, each call to aList spawns exactly one other recursive call, resulting in a <strong>tail recursion</strong> on the Executor’s task queue.</p><p>Such types of errors are extremely hard to debug, because they have a very low footprint in our code and in diagnostic methods like memory profiling, so it only strengthens the point from before about using property getters with caution.</p><p>Still, this doesn’t cause exhaustion of the memory heap, but we are nearly there! Now, let’s the last step.</p><p><strong>What will happen if every call to the property getter spawns more than one recursive call?</strong></p><p>Of course, in standard call stack recursion, this is not possible, because each thread can only insert a new frame to the call stack by calling a function. But since Executors manager their call stack in an internal, heap-backed data structure, this assumption is broken.</p><p>Consider a third variation of our example code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e421b79a4fce804191e32adbddb4993/href">https://medium.com/media/8e421b79a4fce804191e32adbddb4993/href</a></iframe><p>The only change is that now we are evaluating aList twice instead of once, but now take a look at the heap memory graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*Tozy-9kd7VY6_d_HLfvesw.png" /></figure><p>We are seeing a very fast flooding of the heap memory and a tooth-like pattern very similar to the original bug we found in our Android app!</p><p>So what’s going on here?</p><p>When each call to Executor::execute spawns more than one call, it can cause the queue to drain slower than it is filled. Consider the control flow graph of this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*5uK9m9AHSvwu53f8Nd5r_Q.png" /></figure><p>Since each recursive call causes two insertions to the queue, after N insertions, the queue will have roughly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/65/1*qGsvp4divDKbmNIY8_fv8w.png" /><figcaption>2^N — N</figcaption></figure><p>items, which grows exponentially.</p><p>This finally explains why our bug occurs and also how to fix it! Indeed, after inspecting the original code, we found exactly <strong>two</strong> recursive calls to our misbehaved property getter.</p><h4>Step 4: Prescribing a Bugfix</h4><p>In this case, fixing the bug is easy. Instead of calling the propery getter in our function, as a quick-fix we only use the inner state it references, but will completely remove this function call in favor of a future code refactor that will eliminate the use of this anti-pattern.</p><h3>Conclusion</h3><p>We’ve shown a type of bug that’s sometimes easy to diagnose (with the right tools), but could also potentially be extremely hard to find. This was a real life example that affected many mission-critical users, and had to be fixed quick. Along the way, I gave a few tips from my experience on how to become better at debugging, and I am also still learning new insights every day. There are also very good conclusions to be drawn on how to write better, bug-proof code that avoids such spurious issues.</p><p><em>Would you like to read more of these? Please feel free to comment here and tell me what you liked and what you didn’t!</em></p><p><em>Did you have a similar experience finding bugs in your code? feel free to write me and tell me all about it!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf070bca8b0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/advanced-debugging-for-java-kotlin-part-1-hidden-stacks-overflowing-3cf070bca8b0">Debugging in Java &amp; Kotlin — Hidden Stack Overflows in the JVM</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Studio Settings Repository: Improving your work environment with Git]]></title>
            <link>https://mikimints.medium.com/android-studio-settings-repository-improving-your-work-environment-with-git-6eb39bf2bef2?source=rss-ed3c91e2ac7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb39bf2bef2</guid>
            <category><![CDATA[development-environment]]></category>
            <category><![CDATA[jetbrains]]></category>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Miki Mendelson]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 20:36:09 GMT</pubDate>
            <atom:updated>2023-04-27T20:36:09.320Z</atom:updated>
            <content:encoded><![CDATA[<p>Through my humble experience as a developer, I often discovered that maintaining a coherent work environment is crucial, at least for me, to increasing my productivity when writing software.</p><p>I admit, that I too sometimes neglect maintaining my environment, partly due to fear of <a href="https://en.wiktionary.org/wiki/breaking_change">breaking changes</a> in libraries, but also through sheer laziness. I recently took the time to upgrade my environment, and came across a very useful feature: Android Studio’s <em>Settings Repository</em>.</p><p>In short, this allows you to backup your IDE’s settings (theme, plugins, key binding, etc.) to a Git repository, and access them from anywhere. This feature saves time and frustration when you need to reestablish your environment, if you every format your computer or setup a new one.</p><p>To enable this feature, go to File -&gt; Manage IDE Settings -&gt; Settings Repository</p><figure><img alt="Configuring a Settings Repository" src="https://cdn-images-1.medium.com/max/536/1*pPYhw1heFxoi__G-n27gCg.png" /></figure><p>There, you will be prompted to setup an accessible Git repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vme1U8e3A5rbZZzIkdTaYg.png" /></figure><p>You can later change it or manually overwrite the local or remote configuration when needed 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5EZhA4CtnPk8G_ffmwCyw.png" /></figure><p>Whenever you exit the IDE or reinstall plugins, Android Studio will synchronize your settings to the git repository in the background ☁️.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dc3HRah8aVmmCGABgAPOVw.png" /></figure><p>This works with other select JetBrains IDEs, and you can read more <a href="https://www.jetbrains.com/help/idea/sharing-your-ide-settings.html#settings-repository">here</a>.</p><p>I hope you’ve found this little trick useful! Would you like to see more tricks to improve your development experience in the future?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb39bf2bef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern Dialer/Call App with Kotlin + Android Jetpack: Chapter 2 [BroadcastReceiver…]]></title>
            <link>https://mikimints.medium.com/building-a-modern-dialer-call-app-with-kotlin-android-jetpack-chapter-2-broadcastreceiver-c1946da7e649?source=rss-ed3c91e2ac7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1946da7e649</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[room]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Miki Mendelson]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 17:08:14 GMT</pubDate>
            <atom:updated>2022-11-18T10:27:25.908Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Building a Dialer/Call App with Android Jetpack: Chapter 2 [BroadcastReceiver, Room]</h3><p>Read the previous chapter <a href="https://mikimints.medium.com/building-a-modern-call-recorder-with-kotlin-android-jetpack-chapter-1-c0aab354facd">here</a>, and get the full code <strong>here</strong> (<em>soon</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U1un7RP2-XtSzUzc" /><figcaption>Photo by <a href="https://unsplash.com/@nowah?utm_source=medium&amp;utm_medium=referral">NoWah Bartscher</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We’ve previously seen how Jetpack Compose helps us efficiently and quickly build a powerful UI experience. But Compose is not only about UI, and it integrates deeply with other Android architectural components. In this chapter, we will take a look at how phone calls are handled on Android. We’ll use a <strong>Broadcast Receiver</strong> to handle incoming/outgoing calls, and we’ll use <strong>Room</strong> to store these calls locally.</p><p>For this chapter, I assume that you are somewhat familiar with concepts in SQL/database design. If you are not, don’t worry, there are links to guide you all over the place 😎.</p><h4>Part 1: Recognizing calls in Android</h4><p>In Android, applications often need to communicate with other components of the environment. These may be system components such as the networking interface of the device, or other user applications which are currently installed. To do so, the Android SDK offers a (somewhat) convenient form of the <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publisher-subscriber</a> pattern called <a href="https://developer.android.com/guide/components/broadcasts"><strong>Broadcasts</strong></a><strong>.</strong> To receiver broadcasts in Android, an app must implement an architectural component called a Broadcast Receiver. In essence, a receiver implements a single method, onReceive , which is called with a Context and some Intent representing the desired broadcast. To configure which events a receiver is bound to, an <em>intent filter</em> is used. In our case, we will implement the CallBroadcastReceiver, responsible for handling incoming and outgoing calls (for now). Let’s look at the declaration in the manifest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a75ad0a087adf5ef4fdac70d412e94/href">https://medium.com/media/95a75ad0a087adf5ef4fdac70d412e94/href</a></iframe><p>We will go through this declaration step-by-step:</p><ul><li>First, the receiver’s class name is defined, as well as exported=&quot;true&quot;. This is done to ensure that the receiver is visible by other components <strong>outside</strong> the application, and in our case we need it to capture the system events corresponding to call placement.</li><li>Second, an intent-filter is defined, with two possible actions: PHONE_STATE and NEW_OUTGOING_CALL. You can read about both <a href="https://developer.android.com/reference/android/content/Intent">here</a> and <a href="https://developer.android.com/reference/android/telephony/TelephonyManager">here</a>. Also note that the latter action was deprecated in Android API 29, but we will go with it for now.</li></ul><p>Next, let’s look at a simple method to extract the call information from the Intent. To represent the possible call types, I will use an <strong>algebraic data type, </strong>which in Kotlin are usually represented by <a href="https://kotlinlang.org/docs/sealed-classes.html"><strong>sealed classes</strong></a><strong>. </strong>My goal is to represent all possible (finite) states of a phone call in a typed manner, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74d6ee0edc2b21f0cfb699b325497a3/href">https://medium.com/media/b74d6ee0edc2b21f0cfb699b325497a3/href</a></iframe><p>This is good for a few reasons. In Kotlin, sealed classes are determined entirely by the package they are defined in. This means that external code cannot inherit them and extend the inheritance tree. This also means that they are highly constrained and useful for cases where state management needs to be strict. Let’s now consider how we can use this definition in a function that extracts the call state from an Intent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd1ecc9529c549048dde414561b03ba1/href">https://medium.com/media/cd1ecc9529c549048dde414561b03ba1/href</a></iframe><p>In this case, we use the defined intent filters and documented intent extras to determine what the intent contains in each case.</p><p>With this, we can succinctly implement our CallBroadcastReceiver:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12bbe94ddb940c8132b38019d03aeb77/href">https://medium.com/media/12bbe94ddb940c8132b38019d03aeb77/href</a></iframe><p>Here, we do a few things:</p><ul><li>Check that all relevant permissions are granted by using a handy extension function Context.checkPermissions</li><li>If they are indeed granted by the app, we test for the phone call type extracted from the phoneCallInformation function, and handle it accordingly. For now, we just show a Toast message.</li></ul><p>The checkPermissions function is a simple enough implementation as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c20f3e59f89ac40b9a2376b585392393/href">https://medium.com/media/c20f3e59f89ac40b9a2376b585392393/href</a></iframe><p>Running the app, we can test with incoming and outgoing calls to see they are properly recognized by our receiver:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ZASeRe6alGIwQcAllDREtw.jpeg" /></figure><h4>Part 2: Persisting calls to a local database</h4><p>Now that we can recognize incoming and outgoing calls, we would like to persist them in a database. We usually encounter two options for persisting data:</p><ul><li>In the cloud: costly, and requires authenticating each user against our application. However, online databases allow persistence across devices and installations of the application</li><li>Locally: easy, priceless, but only persists information on the installed device.</li></ul><p>For now, we will take a look at implementing a local persistence solution. The <strong>Room persistence library</strong> is a very neat solution that integrates nicely with other architectural components, as we will see shortly.</p><p><strong>Introduction to Room</strong></p><p>First, let’s consider what the official documentation says about Room:</p><blockquote>The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits:</blockquote><blockquote>- Compile-time verification of SQL queries.</blockquote><blockquote>- Convenience annotations that minimize repetitive and error-prone boilerplate code.</blockquote><blockquote>- Streamlined database migration paths.</blockquote><p>This is key to remember: Room is simply an abstraction over <strong>SQLite</strong>. Nothing more! When you consider learning it for your own benefits, it’s worth remembering, because it will make your life much easier.</p><p>Let’s take a look at how these benefits translate to our code. In Room, there are three major components: The database, the data access layer (represented by data access objects), and the data layer (represented by entities). This could not be explained better than this diagram from the official documentation:</p><figure><img alt="Room’s three layer architecture (Credit: Android Developers)" src="https://cdn-images-1.medium.com/max/600/1*jT94pc71uD_A2TPN_E2ulg.png" /><figcaption>Room’s three layer architecture (Credit: Android Developers)</figcaption></figure><p>To best demonstrate how this works, let’s implement each of our layers from bottom to top.</p><p><strong>Entities</strong></p><p>Remember our RegisteredCall class? This acts as our data representation. With room, we can make it into an SQL table <strong>without</strong> changing anything about the structure of the class itself, using annotation classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f8872a30a7b661139f4767f7457f7ba/href">https://medium.com/media/0f8872a30a7b661139f4767f7457f7ba/href</a></iframe><p>To understand what’s going on here, let’s look at a very simple <a href="https://creately.com/blog/diagrams/er-diagrams-tutorial/"><strong>entity relation diagram</strong></a> (ERD) of our database. Since we are only interested in the registered calls, our ERD is painfully simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*SWRICnNSav9efXojLCnTvA.png" /><figcaption>Our app’s Entity Relation Diagram</figcaption></figure><p>Room gives us tools to transfer our Java/Kotlin types into entities, which are schemas that SQL can understand under the hood:</p><ol><li>The PrimaryKey annotation marks a field as a <a href="https://www.w3schools.com/sql/sql_primarykey.ASP">primary key</a>. This means that it <strong>uniquely </strong>identifies each row in the generated table. The autoGenerate = true simply means that if 0 is passed as the value, it is replaced with a unique value generated by the SQL engine.</li><li>The ColumnInfo annotation allows customizing how the specific column associated with a field looks. Room usually knows how to handle fields without this annotation as well, but there’s always a benefit in being explicit here.</li><li>The Entity annotation allows customizing how the table associated with this data type looks like. Here, we set the name of the table.</li><li>Lastly, TypeConverters is a very useful annotation that demonstrates a lot of the power of Room over traditional SQL engines. Since our data type has fields which the library does not know how to serialize (Duration, CallType), we need to explicitly define functions that convert to/from these types and their database representation. In both cases, I chose Int as the best representation for both, since a known enum can be represented by its type indices, and a duration can be represented by a known unit, for example seconds. Both converters are very easy to implement as classes using the TypeConverter annotation:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67aab66422e457e5d0ca209da271f6fb/href">https://medium.com/media/67aab66422e457e5d0ca209da271f6fb/href</a></iframe><p>Notice that this poses a few restrictions that we ought to address:</p><ul><li>Durations less than a second are not representable here. This is ok, because regarding calls, we usually don’t care about such granularities.</li><li>Adding new enum values in the future cannot break the interface. This means that if we add support for more call types (For example: conference, VOIP, etc.), we must do it in a way that does not break rows which are already in the database (For example, adding types only at the end of the enum definition to maintain monotonicity of the indices). In practice, for more complex database schemes, enums will usually be represented as their own SQL table with rows for values, but this is good enough for our needs.</li></ul><p><strong>Data Access Objects</strong></p><p>Data access objects (DAOs) are the middle points between the database and its entities. They are simply interfaces that define what operations can be performed on our entities. For our RegisteredCall entity, we want to be able to list all calls, retrieve a call by its id, insert a new call toe the database, and delete a call. For testing purposes, it would also be useful to implement a method that deletes all calls in the database. Our DAO will like like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f213eb70178ac3c039b8b8af2b645d/href">https://medium.com/media/b1f213eb70178ac3c039b8b8af2b645d/href</a></iframe><p>I’ll explain some of the more interesting parts here:</p><ol><li>Room allows writing methods that invoke generic SQL queries. For example, to list all calls, we invoke the simple query SELECT * FROM registered_calls (This is how we decided our entity table is named).</li><li>Queries can also accept method parameters! For example, we we can get a call by id, with the meta-query SELECT * FROM registered_calls WHERE id == :id. Neat!</li><li>The list() returns a Flow object! What’s that? Essentially, this is a stream that emits objects sequentially in a coroutine context. Room supports this behavior, and will emit an updated list whenever the database changes! This is very useful, because this means that we can easily integrate this behavior into a MVVM architecture. More on that later</li><li>Trivial operations are supported: Insert, Delete. They also take an entity object as a parameter, and serialize it according to its type converters.</li></ol><p><strong>The Database</strong></p><p>All we have to do to complete our Room implementation, is to define a <strong>database</strong>. A database facilitates access to our DAOs, and is also responsible for features such as database migration, which we will talk about in the future. For now, let’s see a simple implementation of our database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9456ba7fe82de5b97b785bcaaa241ca2/href">https://medium.com/media/9456ba7fe82de5b97b785bcaaa241ca2/href</a></iframe><p>Since we only have once DAO and one entity, we define them using the entities field of the @Database annotation, and we define an abstract function to return an instance of the DAO. Room will generate an implementation for this abstract class during compile-time, based on the properties and the function declarations!</p><p>We usually want our database to be a singleton. This is true, because initialization of a database is probably a costly operation, and we only ever use it to facilitate access to DAOs (Which by themselves are not singletons). This is the <strong>factory design pattern</strong>, because we provide a way to get instances of the RecordingClassDao without worrying about the implementation details.</p><p>There are excellent ways to make AppDatabase a runtime singleton in our app, which we will discuss in later chapters when we discuss dependency injection. For now, we will use the classic way of making a singleton in Kotlin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e372ca1d46e6744b00e670928bcb9519/href">https://medium.com/media/e372ca1d46e6744b00e670928bcb9519/href</a></iframe><p>Let’s explain what’s going on here:</p><ul><li>A companion object in Kotlin is a true singleton. This means that it is evaluated only once during the lifetime of the app, and is also thread safe. This is important, because if it were not thread-safe, multiple threads could evaluate it and result in an invalid states of two separate instances of the singleton object across the application lifetime.</li><li>Instead of using the companion object directly, we hold a nullable instance of our own class and use the instance function to evaluate it once on first access.</li><li>Why do we use the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/synchronized.html">synchronized</a> method here? Well, for the same reasons I explained earlier, we want this evaluation to be thread safe, which means that if two threads try to access the object at the same time, they will be synchronized under a shared object monitor. This is still a generally bad method of synchronization in Kotlin, and we will see better ones in later chapters.</li><li>Lastly, we mark the singleton field as @Volatile for the JVM, so that once evaluated, it is immediately non-null in all other threads. Not adding this could result in another thread trying to call instance after the first thread finished evaluating it, and seeing a null object that hasn’t been written to the shared memory yet. Read more about this <a href="https://www.baeldung.com/java-volatile">here</a>.</li></ul><p>Lastly, since we are yet to implement the logic that saves actual calls to the database, we can use our dummyCall method to populate it. Here, we use the RoomDatabase.Callback interface. Our DatabaseCallback implements it, and uses the same DAO and database methods we declared:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c72129a77ca243aabd15607319aee0c/href">https://medium.com/media/8c72129a77ca243aabd15607319aee0c/href</a></iframe><p>We could write our objects directly to the database by using the supplied db object, which allows raw access to the SQLite instance, but this is easier.</p><p>Lastly, we can swap our implementation in the UI to get the call list from the database instead from a dummy list. First, in our MainActivity, we get an instance of our AppDatabase :</p><pre>private val applicationScope = CoroutineScope(SupervisorJob())<br>private val appDatabase = AppDatabase.instance(applicationContext, applicationScope)</pre><p>Then, inside our composable, we can transform our call list Flow into a Compose state with the utility function collectAsState:</p><pre>val recordings = appDatabase.callRecordingsDao().list().collectAsState(initial = emptyList())</pre><p>Then, we can use the state’s value inside the CallList composable:</p><pre>CallList(<strong>recordings.value</strong>) <strong>{ </strong>_, call <strong>-&gt;<br>    </strong>snackbarCoroutineScope.launch <strong>{<br>        </strong>scaffoldState.snackbarHostState<br>            .showSnackbar(&quot;Call recording ${call.id} clicked&quot;)<br>    <strong>}<br>}</strong></pre><p>The full implementation of MainActivity is given here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1bc5c169b0f89b3907e78d004838dfe/href">https://medium.com/media/d1bc5c169b0f89b3907e78d004838dfe/href</a></iframe><h4>Conclusion</h4><p>In this chapter, we introduced the Room persistence library and added support for saving our calls to a locally persistent database. We also wrote a BroadcastReceiver that’s able to detect incoming and outgoing calls. In the next chapter, we will complete this implementation by replacing our dummy calls in the database with actual calls from the receiver. We will also introduce another screen to the app and move between them using <strong>Compose Navigation</strong>. We will also improve our UI and business logic separation by introducing <strong>ViewModels </strong>and the android MVVM architecture. Feel free to follow me if you want to stay updated when more chapters are released 😆.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1946da7e649" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern Call Recorder with Kotlin + Android Jetpack: Chapter 1]]></title>
            <link>https://mikimints.medium.com/building-a-modern-call-recorder-with-kotlin-android-jetpack-chapter-1-c0aab354facd?source=rss-ed3c91e2ac7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0aab354facd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Miki Mendelson]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 21:28:55 GMT</pubDate>
            <atom:updated>2022-11-18T10:26:39.746Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Building a Dialer/Call App with Android Jetpack: Chapter 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VeDA27F9asjy6czM-Gq9w.jpeg" /></figure><p>As an Android developer, I was always fascinated by the tremendous progress the development ecosystem has gone through in recent years. From the Android Support libraries, to the warm adoption of Kotlin as the go-to language for native Android, and the introduction of Android Jetpack, Google constantly aims to make developing Android apps easier, faster and more scalable.</p><p>With the recent introduction of Jetpack Compose, I began to wonder what it would be like to build an Android application from scratch, using modern libraries, best practices and architectural patterns. While maintaining old Android code is one thing, starting with a clean slate is something completely different. Looking at potential apps to make, I came across an idea to make an automatic call recorder. This unfortunately turned out impossible due to Google’s restrictions on call recording in new Android versions. The next closest thing would be a call manger/dialer app. I decided to take this as a personal project, and share my development process here ✨. This is the first chapter of so-and-so in a series of articles, where I will work on a full-fledged application. My goal is to maintain a positive learning experience while creating something usable and nice-looking.</p><p>Ok, enough chatter. Let’s dive in 🔽</p><h3>Chapter 1: Introduction to Jetpack Compose</h3><p>For this first two-part chapter, we will focus in preliminaries, setting up our project, and designing a very basic user interface (UI) for our app. This article roughly covers the following topics:</p><ul><li>Jetpack Compose for Android</li><li>Compose UI: Composable elements, Modifiers, Theming</li></ul><p>I also assume basic knowledge of Kotlin, including extension methods, delegation and coroutines.</p><h3>Part I: Environment Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JF9sf8HBKEuamShaPn-iDQ.png" /><figcaption>Android Studio Arctic Fox</figcaption></figure><p>First, let’s make sure we can run an Android app with Compose support. To do so, make sure you have an updated version of <strong>Android Studio Arctic Fox</strong> (Currently, it’s version <em>2020.3.1 Patch 1</em>) or a newer distribution. This will ensure that you benefit from smart editor features and the compose preview.</p><h4>Creating our Project</h4><p>Let’s create a new project with Compose support. Enter the <strong>New Project</strong> window, and select “<strong>Empty Compose Activity</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckVckdNF7SzyJnc15lnRdQ.png" /><figcaption>Android Studio Arctic Fox adds support for creating an empty Compose application.</figcaption></figure><p>Fill in the standard fields as you would (application name, package name) and set the minimum SDK to <strong>API 21 (Lollipop)</strong>, and click <strong>Finish</strong>. I’m going to name my project <strong><em>Recordio</em></strong>, because it sounded cool in my head and has the word “record” in it 🙂.</p><h4>Setting the Java Version</h4><p>Since new projects are created with Gradle 7 as the build system, you should also make sure that you have at least Java 11 installed. To ensure that your project uses this version, you can roughly follow this checklist:</p><ul><li>In your application-level build.gradle (Located at app/build.gradle) make sure that sourceCompatibility and targetCompatibility are set to JavaVersion.<em>VERSION_11 </em>(They are located under android -&gt; compileOptions). If you have a different compatible version installed, you can use it instead (For example, JavaVersion.<em>VERSION_12</em> will also work).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda70765b14ca48657d722df42dcd8a2/href">https://medium.com/media/cda70765b14ca48657d722df42dcd8a2/href</a></iframe><ul><li>Set a compatible Gradle JDK under <strong>Gradle Settings</strong>. You can access them from the <strong>Project Structure</strong> window, under <strong>SDK Location </strong>(<strong>Control+Alt+Shift+S</strong> on <em>Windows/Linux</em>, <strong>⌘;</strong> on <em>macOS</em>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1MspqFeYjkApet7Lwgn3w.png" /><figcaption>Set the Gradle JDK to a compatible version.</figcaption></figure><p>When Android Studio finishes making the project, we get our first glance at MainActivity.kt, the main entry point for our application.</p><h4>Introducing Jetpack Compose</h4><p>Jetpack Compose was recently released under a stable 1.0 version, which means it is no longer under beta, and is considered production-ready. Let’s look at how Google describes it:</p><blockquote>Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. [<a href="https://developer.android.com/jetpack/compose/tutorial?hl=en">Source</a>]</blockquote><p>First, it is important to note that Jetpack Compose it <strong>Kotlin Only</strong>. The main reason being that Compose makes heavy use of Kotlin’s <em>coroutines</em> (If you are not yet familiar with the concept, the <a href="https://kotlinlang.org/docs/coroutines-guide.html">official guide</a> is a good place to start).</p><p>Let’s take a look at the main activity that Studio generated for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbb61754dd931d0ecf807f2da3642980/href">https://medium.com/media/bbb61754dd931d0ecf807f2da3642980/href</a></iframe><p>Let’s briefly analyze what’s going on here.</p><ul><li>Our MainActivity inherits from a ComponentActivity , instead of the traditional AppCompatActivity. This is done to enable use of the new setContent extension method, which accepts a @Composable block</li><li>We are also given two top-level functions which are @Composables: Greeting(name) and DefaultPreview. Greeting composes a simple Text composable, which is the Compose equivalent for the traditional TextView.</li><li>Our activity’s onCreate method calls the new Compose setContent extension method, which is in charge of building the Compose UI. In it, we compose two blocks: a RecordioTheme (The name is derived from how we named our application, <em>Recordio</em>), which composes a Greeting</li><li>Looking at DefaultPreview, it is built of the same composition of elements as the setContent block, and it is not used anywhere. The only difference is that DefaultPreview is annotated with @Preview, which allows it to be previewed from Android Studio, much like the layout preview in XML layouts.</li></ul><p><strong>Note</strong>: @Preview annotations can only be applied to functions annotated with @Composable, which receive no arguments. This means that the previewed composable must provide default values for any arguments it accepts. More on that later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*H-talafOuabVkfmxedNFJQ.png" /></figure><p>If you set up everything successfully up to this point, you should be able to run your application on a physical device or emulator, to see the resulting screen, which should look something like the screenshot on the left.</p><h3>Part II: A Basic UI for the Main Screen</h3><p>Let’s begin by building a basic UI for our project. Before diving into code, it’s important to note some key points:</p><ul><li>Traditionally, Android uses activities and fragments to separate screens and independent flows. In Compose, applications are designed to run with a single-activity architecture. This makes it easy to introduce complex navigation flows with <strong>Compose Navigation</strong>, and all navigation logic is handled by the Compose runtime.</li><li>This also means that the standard activity and fragment lifecycles do not apply here. Instead, Compose defines different side-effects that can act as lifecycle callbacks. More information <a href="https://stackoverflow.com/questions/68962458/how-are-android-activities-handled-with-jetpack-compose-and-compose-navigation">here</a>.</li></ul><p><strong>Data Model</strong>: In a later chapter, we will use the <a href="https://developer.android.com/training/data-storage/room">Room persistence library</a> to save and retrieve call recordings, but for now we will define a simple data model to interact with the UI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab7f5d971b0ff6abf5318a41cb680304/href">https://medium.com/media/ab7f5d971b0ff6abf5318a41cb680304/href</a></iframe><p>We will also provide a simple method to generate dummy data, for display purposes only:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f17f6172028e199f986a0682af5bc4db/href">https://medium.com/media/f17f6172028e199f986a0682af5bc4db/href</a></iframe><p>You can find the full RegisteredCall.kt file <a href="https://gist.github.com/mikimn/ad9bdd3b31950f7b4c9ef6122d8fe952">here</a>.</p><h4>The main screen</h4><p>Our main screen is going to be very simple, with just a toolbar containing a title, and a scrollable list of call recordings. Clicking a specific recording will open the <strong>details screen</strong>. Pretty simple stuff!</p><p>Ok, preliminaries first, let’s add a few dependencies to our app-level build.gradle :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/352391f36e766d85a0fa55f63d5c3182/href">https://medium.com/media/352391f36e766d85a0fa55f63d5c3182/href</a></iframe><p>coreLibraryDesugaringEnabled and desugar_jdk_libs are needed in order to enable Java 8+ APIs without a minimum Android API level (by <a href="https://developer.android.com/studio/write/java8-support#library-desugaring">desugaring</a>). The other dependencies are for Jetpack Compose support, Kotlin extensions (core-ktx) and support libraries.</p><p>Lastly, add the compose_version variable to the top-level build.gradle file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a9a0c29f000c39727876f94ec3d2e2e/href">https://medium.com/media/6a9a0c29f000c39727876f94ec3d2e2e/href</a></iframe><p>It’s finally time to write our first Composable! Remember that in Compose, UI elements are functions annotated with @Composable, and manage their own local state. Let’s look at how our recordings list would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/355332e29709150f31350f07be43b172/href">https://medium.com/media/355332e29709150f31350f07be43b172/href</a></iframe><p>As before, we’ll go through each of the components here in details.</p><ol><li>CallL receives the list of RegisteredCalls and an onClick listener, which will handle click events for the list items.</li><li>We use a LazyColumn composable, the equivalent of RecyclerView in the Android view system. The LazyColumn is similar to the Column element, with the main difference being that the first loads elements in the list only as they appear on the screen.</li><li>Since we load elements to the screen lazily, LazyColumn does not accept a composable block. Instead, it defines a <em>LazyListScope DSL</em> which allows us to describe <em>how</em> the elements are created. In our case, we use the itemsIndexed method, which receives our list of items, and emits composables which are aware of their index in the list. If you are unfamiliar with DSLs in Kotlin, read more <a href="https://developer.android.com/jetpack/compose/kotlin#dsl">here</a>.</li><li>Lastly, our list also needs to remember it’s scroll state. <strong>Remember</strong> that a composable can always be rebuilt, so without the list knowing what was its last scroll state, each redraw of the composable would result in the UI “jumping” to the top of the list. For that reason, we use rememberLazyListState(), which creates a state object that we can pass to the lazy list. Hopefully we will discuss state objects in more details at a later chapter 🙂.</li></ol><p>Now, let’s define how a single recording item in the list looks, our CallItem composable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16d737222b5e2ab78a9c83768f8fc58e/href">https://medium.com/media/16d737222b5e2ab78a9c83768f8fc58e/href</a></iframe><p>Ok, once again let’s look at everything that’s going on here in detail:</p><ol><li><strong>Modifiers</strong>: Modifiers are a very convenient way to add extra behavior to Compose UI elements. What’s extra behavior? Well, it can be the size, shape, semantics, boundaries (padding) and motion of the elements. It can also be used to attach different user interactions such as pressing, focusing, and more. Read about it and view the full list of available modifiers <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier">here</a>. <br>It is also worth noting that the Modifier interface is <em>fluent</em>. If you are unfamiliar with the concept, don’t worry, all it means is that the interface supports method chaining, because every method returns the instance on which it was invoked (this). <br>For example, consider the modifier we give to the top-level Card element: Modifier.fillMaxWidth().clickable(onClick = onClick) . This modifier means “Make this element fill the maximum width of the screen, and also make it clickable with onClick as the click listener”.</li><li><strong>Elements</strong>: Here, we use a Card element from the Compose Material library, which gives us a Material Design card. We also use the self-explanatory Row element to horizontally lay out a Box and Column. The Box element contains an icon indicating the type of call which was recorded, and the Column lays out some textual information (The phone number/contact name associated with the call, and the duration of the recording). We also define some extension methods to make the code a bit more readable and verbose. You can find them <a href="https://gist.github.com/mikimn/82884000a0fb79004a4cc6c1a7fff5d8">here</a>.</li><li><strong>Theming</strong>: The style attribute passed to the Text element allows us to control the look &amp; feel of the text. MaterialTheme stores the application-wide theme, and gives us access to styling for layouts, typography and color. More information <a href="https://developer.android.com/jetpack/compose/themes">here</a>. For now, we won’t get too much into theming, but we will dive deep into theming in the coming chapter, when we give our application a fresh look!</li></ol><p><strong>Previewing the User Interface</strong>: Now that we are mostly done with the main UI parts, we would like to preview how our components look so far. Luckily for us, Compose gives us this option out-of-the-box with the @Preview annotation!</p><p>When defining a preview component, we define an @Composable function with no parameters. As such, all of the initial parameters must be known in advance. We can preview our CallItem element by passing in a dummy recording, using the functions we created earlier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61980d2d022fdd4e0462f19187f6b916/href">https://medium.com/media/61980d2d022fdd4e0462f19187f6b916/href</a></iframe><p>Building the project and looking at the design screen in Android Studio, we should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4VfP4z81BZO6trgSZiLSQ.png" /></figure><p>Looking good! Let’s bind everything together by rewriting the main activity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ee897c5742c1ee69764f24755e8874f/href">https://medium.com/media/4ee897c5742c1ee69764f24755e8874f/href</a></iframe><p>We’ve added a TopBar element that only displays a title, and we’ve initialized our CallList with 100 dummy calls. When a recording item is pressed, we show a sanity check snack bar. Our layout is encapsulated with a Surface, which is in charge of applying background color to the app, a Scaffold , which handles the structured look &amp; feel of a Material Design page, and a RecordioTheme , which is a MaterialTheme generated by AndroidStudio for our application. We’ll dive into it in the coming chapters.</p><p>Finally, we run the app and get a first look at our creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*sdRGUIgivuvPu6hNaplXGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*gummXoKpWY_IgA37Wi6CBA.png" /></figure><p>Jetpack Compose for Android is a powerful and versatile toolkit for modern UI design, and we managed to create a simple, yet very nice-looking interface with just a few hundred lines of code in Kotlin.</p><p>In the next chapters, we will complete work on the user interface by introducing the <strong>details screen</strong>, and we will navigate between the two using <strong>Compose Navigation</strong>. We will implement our recording persistence and business logic using <strong>Room</strong>, <strong>ViewModel</strong>, <strong>LiveData</strong>. We will combine dependency injection using <strong>Dagger+Hilt</strong>, and of course, we will implement automated call management with services and broadcast receivers. Feel free to follow me if you want to stay updated when more chapters are released 😆.</p><p>Read <strong><em>chapter 2</em></strong> <a href="https://mikimints.medium.com/building-a-modern-dialer-call-app-with-kotlin-android-jetpack-chapter-2-broadcastreceiver-c1946da7e649">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0aab354facd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>