<?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 Moti Bartov on Medium]]></title>
        <description><![CDATA[Stories by Moti Bartov on Medium]]></description>
        <link>https://medium.com/@motibartov?source=rss-efa4586abd94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*auzbg9yh2-dNYY87.</url>
            <title>Stories by Moti Bartov on Medium</title>
            <link>https://medium.com/@motibartov?source=rss-efa4586abd94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:00:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@motibartov/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[Flutter Background Tasks]]></title>
            <link>https://medium.com/swlh/flutter-background-tasks-26815e1c4046?source=rss-efa4586abd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/26815e1c4046</guid>
            <dc:creator><![CDATA[Moti Bartov]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 13:51:05 GMT</pubDate>
            <atom:updated>2023-03-14T09:06:39.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0BVmYD7v7bnIAUkzCZjRNA.jpeg" /></figure><p>Flutter is a great framework for building beautiful mobile apps with a single code base written in Dart programming language both for Android and IOS.</p><p>A mobile app may require to run some background tasks such as listening to location changes, monitor to the user Activity or Motion (Steps, Running, Walking, Driving etc’), subscribe to system events such as BootComplete, battery and charging, searching for BT or WiFi network and so on.</p><p>In Android for example, we can have a few background tasks running while the app is actually closed! <br>We can define a BootComplete Broadcast Receiver which will run right after the phone boots, we can then schedule background tasks using the WorkManager or AlarmManager with a Service to execute code in the background.</p><p>Of course, some of these tasks requires user’s permission, and may even show a notification which indicates that this app has something running in the background. As long the user knows about this, and approved this, these tasks may work in the background without a problem.</p><p>In IOS, background tasks has tougher restrictions but still, there are ways to run some background tasks but with much more limitations.</p><p>Speaking about Flutter app and background tasks, one thing should be clarify is that usually, these tasks are running in the native side of each platform!! The logic responsible for registering and managing a background task (Worker, Alarm, Service, BroadcastReceiver etc’) are written in native code like Kotlin, or Swift. But, as we know, a Flutter app logic is written in the Dart side, this code builds the UI of course, and also may manage persistence data, user management, network infrastructure and tokens, and much more.</p><p>If we want to share data between the Dart side and the native side we can do this with Flutter MethodChannel and EventChannel. <br>In Flutter, MethodChannel and EventChannel are the way to send and receive messages to and from the native side to the Dart side, and they are used in Flutter plugins.</p><p>Let’s assume that we’re interested with BootComplete and and battery status and process these events in Dart in background.</p><p>Usually, sharing data between the Dart side and native side through MethodChannel and EventChannel is easy when the app is in foreground, but what can we do if we want to start Dart from native side and start a background <a href="https://blog.codemagic.io/understanding-flutter-isolates/">isolate</a>?</p><p>Let’s find out!</p><p>Before we continue, I highly recommend that you will be familiar with Flutter Plugins and how to create one, as the examples will be based on a Flutter Plugin implementation which are detailed in the <a href="https://docs.flutter.dev/development/packages-and-plugins/developing-packages">documentation</a></p><h3>Start your Dart Engine (from background!)</h3><p>Flutter main isolate (the entry point) starts when the app launches in the main() function. Fortunately, it appears that it’s also possible to start the Dart VM from native and invoke a <strong>global function</strong> in a background isolate (a secondary entry point). <br>The key for this is to have that entry point reference identifier — <strong>callbackRawHandle </strong>available in the native side whenever the app wakes up in the background.</p><h4>What ChatGPT says about Dart Callback Raw Handle</h4><blockquote>In Dart, a “callback raw handle” is a reference to a low-level implementation of a Dart function that can be passed to a native platform API.</blockquote><blockquote>A raw handle allows you to bypass the Dart VM’s normal type checking and invoke the function directly from native code. This is useful when you need to pass a Dart function as a callback to a native library. Raw handles are used in situations where you need to perform some operation on Dart code from the native side of your application.</blockquote><p>There are a few steps that need to be done in order to run call Dart code from native in background, and before I go into details and code I want to show this in a diagram and then explain it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*j3k3lcjG-6MjAIiW3cGWWg.png" /></figure><p>Lets go over the diagram and explain each part, as we can see, there are 6 major steps:</p><ol><li>Define Dart <strong>callbackDispatcher</strong> global function, this actually is just a global function with no parameters which will act as a <strong>secondary entry point</strong> and run in a background isolate which called <strong>directly</strong> from native side.</li><li>This part has also 3 steps:</li></ol><ul><li>When the app first launch, pass the <em>callbackDispatcher</em> function to the plugin as a parameter with an api</li><li>In the plugin, produce the <em>callbackDispatcher</em> <strong>RawHandle</strong> using <em>PluginUtils::toRawHandle </em>method and forward it to the native side of the plugin (through a MethodChannel) — 2&#39;.</li><li>Save the <strong>RawHandle</strong> value (a Long number) in a persistence storage in the native side so it will be available in the future — 2&#39;’</li></ul><p>The above part can be done <strong>once</strong>, we save the <strong>RawHandle</strong> in a persistence storage and when the app wakes up in the background, it will be available from the storage and will be used for calling the <em>callbackDispatcher</em> directly from the native side.</p><p>3. When the app wakes up in the background (e.g. a BootComplete — Background Process Initializer), retrieve the RawHandle from persistence storage</p><p>4. Initialize the <em>FlutterEngine</em> and <em>FlutterLoader</em> in the background</p><p>5. Get the <em>FlutterCallbackInfo</em> using the RawHandle</p><p>6. Use the <em>DartExecutor</em> with the <em>callbackInfo</em> (from step 5) to <em>executeDartCallback</em>. This will invoke the <em>callbackDispatcher</em> function in the Dart side!</p><p>7. When the <em>callbackDispatcher</em> invoked, you can then register to other events in your plugin and process them in the Dart side in the background or use other plugins!</p><p>As said, the <em>callbackDispatcher</em> is just an entry point for Dart background isolate.</p><h3>100 Lines of code worth 1000 words</h3><p>Lets break the above steps into code examples:</p><h4>Create the callbackDispatcher in main.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b76ee521bcb2fc9b5c2203ebd42aab/href">https://medium.com/media/61b76ee521bcb2fc9b5c2203ebd42aab/href</a></iframe><p>In above code snippet, we’ve create the <em>appCallbackDispatcher</em> global function in main.dart, this is just a global function with no parameters and it will be the <strong>secondary</strong> <strong>entry point</strong> of theDart side, it will be called directly from native and will run in a background isolate. <br>Then, in the <em>main()</em> function in line 11, we pass the <em>callbackDispatcher</em> to our plugin with an api, as a parameter.</p><blockquote>Notice the <em>@pragma(‘vm:entry-point’) </em>annotation, this is necessary because this function has no calls in the Dart side (it called directly from native) so the AOT tree-shaking compiler may drop it during production build. This annotation prevent from the compiler to drop this function.</blockquote><p>Lets move to the plugin side and see how it looks like:</p><h4>Get the RawHandle in plugin Dart code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b262aba88f219e0a804579be5ff2c278/href">https://medium.com/media/b262aba88f219e0a804579be5ff2c278/href</a></iframe><p>In the code sample above, we see a typical Flutter plugin Dart-side.<br>Here we’re interested in the <em>registerCallbackDispatcher</em> api, this is the api we call from the app <em>main()</em> function with the <em>callbackDispatcher</em> as a parameter. Then in lines 13 and 15, we’re getting its <strong>RawHandle </strong>using the <em>PluginUtilities </em>and<em> toRawHandle()</em> method.<strong> </strong>Then, in line 17, we forward it to the native side with the methodChannel. In the diagram, this part refers to steps 2 and 2&#39;.</p><h4>Save the RawHandle in Persistence Storage (Native-Side)</h4><p>Lets head over to the plugin native side and see how it handles <em>registerCallbackDispatcher </em>api</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6187536f18c0ec2a9747c46ea388131f/href">https://medium.com/media/6187536f18c0ec2a9747c46ea388131f/href</a></iframe><p>The above code example has two parts:</p><ol><li>In the first part we see the MyPlugin.kt file which is the plugin native side written in Kotlin. We’re interested in the <em>registerCallbackDispatcher</em> api which is called from the Dart-side, and in line 18, we’re getting the <strong>dispatcherHandle </strong>that passed as a parameter when called from dart. <br>Then in line 23 we save it in a <em>SharedPreference</em> persistence storage.</li><li>The second part is just a helper class for saving and reading from <em>SharedPreferences</em></li></ol><p>This explanation refers to part 2&#39;’ in our diagram.</p><h4>Starting Dart engine from background</h4><p>Here comes the part that is the hardcore of this story, we want to start the Dart Engine and VM from background but without starting the main isolate and the UI part. As we see in the diagram step 3 it says Background Process Initializer. For simplicity, I’ve chosen a BootComplete BroadcastReceiver for starting the Dart VM once the phone reboots, but its up to you to decide where is the right place for that depends on your app requirements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67e5e16f3884baf2d95c15158921249a/href">https://medium.com/media/67e5e16f3884baf2d95c15158921249a/href</a></iframe><p>In the code above, we see a typical BroadcastReceiver which invoked when phone boot completed. From the onReceive we start and calls our dart callbackDispatcher with two major steps (4, and 5 in the diagram).</p><ol><li><em>initializeFlutterEngine </em>method:<br>- Create a FlutterLoader object and checks if it’s initialized<br>- Starting and waiting for initialization to complete on lines 25–26<br>- Getting the app <em>BundlePath</em> which is the app root path</li><li><em>executeDartCallback</em>:<br>- Create FlutterEngine object in line 37<br>- Next in line 38, getting the <strong><em>callbackDispatcher</em></strong> handle which we kept previously in <em>SharedPreferences<br></em>- Checking that the handle valid, then getting the <em>CallbackInfo</em> with the RawHandle as a parameter (line 41)<br>- Once we have the <em>callbackInfo </em>we then use DartEngine.dartExecutor to call the callbackDispatcher callback in the Dart side!! part 5 in the diagram.</li></ol><p>This, will call the <em>callbackDispatcher</em> in the Dart side in background directly from native code!</p><p>To summarize, once the phone reboots, it will start the Dart Engine in behind the scenes.</p><h3>Mission Accomplished!</h3><p>As mentioned earlier, the <em>callbackDispatcher</em> is just a secondary entry point similar to <em>main()</em> function. Once it launched, apparently, dart apis and third party plugins are now available so we can run any dart logic or interact with other plugins in the background isolate while the UI part is dead!</p><p>For example, our own plugin can provide an EventChannel with event stream for any event we choose, this events stream can be listen inside the <em>callbackDispatcher</em> and get the events in the background, in Dart side.</p><p>I must say that the following part has nothing to do with the background isolate theory explained above, this is just an ordinary plugin features which provide Dart apis for sending and getting messages from native side.</p><p>The only thing is that now, we can interact with it from the callbackDispatcher, once it was invoked in background.</p><p>Lets see some code and then I will explain it</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c73886c3210f817b4671e7c944076e61/href">https://medium.com/media/c73886c3210f817b4671e7c944076e61/href</a></iframe><p>The code above has 3 parts:</p><ol><li>The first part is again the plugin apis, but at the bottom we now provide an api for listen to messages through the EventChannel, and also there is additional api, for example, to start monitor device charger and battery status. The events will be sent back through the EventChannel</li><li>The second part is the plugin native side, and in lines 16 and 17, we’re setting a StreamHandler with a dedicated class</li><li>Last but not the least, the PluginEventEmitter class, this is the class which will send messages to dart side.</li></ol><p>At the bottom of PluginEventEmitter class, I’ve defined a sealed class for events which will be sent to dart, on this example there are 2 events: BootComplete and BatteryLevelStatus</p><p>The PluginEventEmitter will also cache events until dart will listen on the EventChannel.</p><p>Lets see how we use this in our callbackDispatcher:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0fcb2c986912a0022b6130b45851110/href">https://medium.com/media/f0fcb2c986912a0022b6130b45851110/href</a></iframe><p>In the callbackDispatcher (which invoked from native after boot complete right?) we now registering to our own plugin events, and then we call <em>startPowerChangesListener </em>and the events will be<em> </em>catched in the listener.</p><p>So, when we reboot the phone, the callbackDispatcher will be called and all of this will be run in the background! And as long as the process is a live (which is a subject for another article..) events will keep coming to the listener in the background!</p><h4>Example project source code</h4><p>Please refer to my example project on <a href="https://github.com/moti0375/charger_status">github</a> with full source code!</p><h3>Summary</h3><p>This pattern is has its drawbacks, it is required that the app will be opened at least once for registering the callbackRawHandle. <br>I must say that at the beginning and still, I’ve found this pattern not the most easy to understand and implement (an understatement), and I hope in the future the Flutter team will come up with more easy solution.</p><p><strong>Thanks for reading, happy coding!</strong></p><p>Checkout the video!</p><h3>Flutter app starts in background video</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcOsKzRNF8UA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcOsKzRNF8UA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcOsKzRNF8UA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/871289482f1c5db3c3fc249d7a7504d8/href">https://medium.com/media/871289482f1c5db3c3fc249d7a7504d8/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26815e1c4046" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/flutter-background-tasks-26815e1c4046">Flutter Background Tasks</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Custom Button With Centered Progress Indicator]]></title>
            <link>https://medium.com/israeli-tech-radar/android-custom-button-with-centered-progress-indicator-ae329d0687d?source=rss-efa4586abd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae329d0687d</guid>
            <category><![CDATA[android-views]]></category>
            <category><![CDATA[android-customview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Moti Bartov]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 16:14:57 GMT</pubDate>
            <atom:updated>2021-03-20T12:30:32.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MeZ82ZGV0WZH43skjs6iw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Denny Müller</a> on <a href="https://unsplash.com/s/photos/android?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Recently, I’ve got a simple task in a project I am working on. <br>I had to create a designed button with a centered progress indicator inside of it.</p><p>The button should have 3 states:</p><ul><li>Enabled</li><li>Loading</li><li>Disabled</li></ul><p>In Enabled state, it should show text while in Loading state it should show a Circular Progress Indicator (which can be native or any custom view such as Lottie animation view) and in Disabled state it should show text but grayed out.</p><p>Here is the final look according to the design!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnH0jZdKiNdX46LaBrbmBA.png" /></figure><p>What sounds like a simple task turned out to be not so straight forward and easy to do! <br>As I’ve looked for a way of how I can implement such view, I thought that I will just create a custom view that extends some Android Button class, but if you will look on the Button classes you will (or not) be surprised that those actually extends nothing else but a TextView!! <br>So how I can extend a View class and then add and manipulate additional Views on it? <br>And also, the biggest part of this of course is the styling and theming!</p><p>After all, I want to make my custom buttons to be reusable, easy to use and with different styles like rounded corners, ripple effect and any color.</p><p>OK! I can do it!!</p><p>When I realised that extending Button is not an option, I thought that extending a ViewGroup like a RelativeLayout or ConstraintLayout will be much better. A ViewGroup has child views inside of it, they can be manipulated and it’s easy to change their visibility and state. <br>I thought, if a TextView can behave as a button then then so a ViewGroup can, it’s all matter of styling and theming. <br>Finally I’ve chosen RelativeLayout, I like it, it’s simple and easy to work with.</p><h3>First Layout First</h3><p>I’ve started with designing my custom button layout, which looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a593efb56f1e95e029a8c93a70baef/href">https://medium.com/media/62a593efb56f1e95e029a8c93a70baef/href</a></iframe><p>As you can see, its just a simple RelativeLayout with a centered TextView and for the progress indicator I’ve chosen to use LottieAnimationView.</p><p>One important thing here, you may look on line 13 in the XML, the TextView <strong><em>android</em></strong>:<strong><em>textAppearance</em></strong> attribute which set to be<br><em>“?android:attr/textAppearanceButton”, </em>this attribute is the one that sets buttons default text appearance right from the app theme! If we will override it in our app theme, it will effect this TextView here. We will see this further down in the styling and theming part of this article.</p><h3>Show Me The Code</h3><p>Now that we have the layout ready, its time to see the code that it is associated with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eb630ad606a4bd4d9987319baaa693e/href">https://medium.com/media/7eb630ad606a4bd4d9987319baaa693e/href</a></iframe><p>Let’s go over the code and see all about it, and that is so simple.</p><ol><li>First, notice as I mentioned that the ProgressButton class extends RelativeLayout</li><li>On lines 10–14 the init block, first, inflating the layout and then on lines 12–13 initialising the childs views using findViewById</li><li>Next, on line 14, calling the loadAttr() method for getting styleables attributes for the button initial state! I’ve defined a few styleables so they can be set in the custom view xml. The attributes are:</li></ol><ul><li>text — Setting the button text</li><li>loading — For setting initial loading state from xml</li><li>enabled — For setting initial enabled/disabled state</li><li>lottieResId — For setting any lottie animation resource from xml</li></ul><p>4. On lines 30–34, applying the initial values to the child views, and also setting the whole view enable state. Later, this enable state will change the appearance thanks to a style and selector background drawable.</p><p>Next, on lines 37–46, <em>setLoading</em> method for changing the button loading states! When it is loading, the <em>TextView</em> is GONE and the progressBar is VISIBLE, when its not loading, the <em>TextView</em> is VISIBLE and the progressBar is GONE.<br>Notice also that when it is in loading state I am setting it so it will be not clickable.</p><p>On lines 48, a method for setting the text in code, for any purposes.</p><p>Last but not the leaset, on lines 52–55 overriding the <em>setEnabled</em> method for setting the whole view (The parent RelativeLayout) enable state and also the enable state of the <em>TextView</em>, this is important as you may want to have different text colors when the button is disabled. <br>Thanks to the <em>“?android:attr/textAppearanceButton” </em>attribute I’ve mentioned earlier, we can have any text styling for different states. I will show all styling in the next sections.</p><h3>Do It With Style</h3><p>After complete with layout and code, all we have to do now is connect a set of styling and theming. This part is a little bit tricky, but here is how I’ve managed it. <br>BTW, I really encourage you to go over this <a href="https://medium.com/androiddevelopers/whats-your-text-s-appearance-f3a1729192d">article</a>, which explains how text appearance, theming and styling works in Android</p><p><strong>Define a Theme in style.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/accd8f2aa118825ef864593f85be774d/href">https://medium.com/media/accd8f2aa118825ef864593f85be774d/href</a></iframe><p>The above xml defines two attributes which will be applied as a <strong>theme</strong> to the button custom view.<br>As we mentioned earlier, the <em>textAppearanceButton</em> attribute will effect the text that is in the <em>TextView</em> that in the button layout.</p><p>Next, the colorControlHighlight attribute will effect the view ripple effect when clicked. This is also an attribute that comes from the app theme which we override just for this custom view.</p><p><strong>The textAppearance styling:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9eabe2ac700131d2d3c191ee8cf1071/href">https://medium.com/media/e9eabe2ac700131d2d3c191ee8cf1071/href</a></iframe><p>In the above xml we set the text appearance, first we define a base <strong><em>TextAppearance.Body.White</em></strong> block with the font family, text style, size and the base color. <br>Next, a specific <strong><em>TextAppearance.ProgressButton.Black</em></strong> block for the black button, this block inherit from the base block but overrides the <em>android:textColor </em>attribute, as the text color should be different when it is disabled so I defined a selector for it.</p><p>Last but not the least, the selector for the black button text color, with different color for disabled state.</p><h3>What Is Your Background?</h3><p>Of course, any view should have a background right? <br>So is our nice little custom button, the way we do it is by defining some drawable with shape and selector just we do in any other view!</p><p>First, lets define the background drawable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/432cfa084e9ce430983250338e011875/href">https://medium.com/media/432cfa084e9ce430983250338e011875/href</a></iframe><p>Notice that the ripple color attribute is colorControlHighligh, thats right! We’ve override it in our theme! Cool! <br>Now, we need to define the <strong>shape</strong> and the <strong>selector</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff410b665096f366d9cdf2d01154ee7/href">https://medium.com/media/6ff410b665096f366d9cdf2d01154ee7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deecd8b61ca1a4f3f1a0238ae4495911/href">https://medium.com/media/deecd8b61ca1a4f3f1a0238ae4495911/href</a></iframe><p>The above three xml’s completes the view background!!</p><p>Now that we have a theme and background ready we should combine them both together! This will be done in another style block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9641ad27adaa287a61df7a9943cae69/href">https://medium.com/media/f9641ad27adaa287a61df7a9943cae69/href</a></iframe><p>Notice that in the above style xml, we defined an <em>“android:theme”</em> attribute and gave it the theme that has been defined earlier. This will apply that theme to the view. <br>Next, we’ve set the “android:background” attribute with the drawable which includes the shape and the selector!</p><p>For any new color or shape, we will have to create a bunch of styling xml as described above! But when using it we should take only the last style block which combine both the theme and the background. You may look in the example in the next section!</p><p>Thats it!! Everything is ready for use!</p><h3>I’ve Built It! I Want To Use It!!</h3><p>All right! This is it! It’s time to use our nice little button in a Fragment or Activity. First, let’s put it in a layout!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a768d50818fa17785237bacf3f929bf1/href">https://medium.com/media/a768d50818fa17785237bacf3f929bf1/href</a></iframe><p>Using the new ProgressButton is simple as just putting it in a layout and just set the style for the preferred color!</p><p>Now in our Fragment, we can use binding to access it and use it!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0c420babc9c54110dfebc4512e373f6/href">https://medium.com/media/a0c420babc9c54110dfebc4512e373f6/href</a></iframe><h3>Summary</h3><p>As you may see, such a simple looking task requires some effort to implement in the traditionally Android and View native framework. I wonder if maybe Jetpack Compose will bring new possibilities for making Android UI manipulation much easy with the ideas of Widgets and composition!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae329d0687d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/israeli-tech-radar/android-custom-button-with-centered-progress-indicator-ae329d0687d">Android Custom Button With Centered Progress Indicator</a> was originally published in <a href="https://medium.com/israeli-tech-radar">Israeli Tech Radar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say Goodbye to Dagger, Hello Hilt]]></title>
            <link>https://medium.com/swlh/say-goodbye-to-dagger-hello-hilt-470f0963dca7?source=rss-efa4586abd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/470f0963dca7</guid>
            <category><![CDATA[android-hilt]]></category>
            <category><![CDATA[android-di]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dagger-android]]></category>
            <dc:creator><![CDATA[Moti Bartov]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 15:00:26 GMT</pubDate>
            <atom:updated>2021-01-20T09:47:53.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFqoKDrDINT19weqKyTQcA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mavrick?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ricardo Cruz</a> on <a href="https://unsplash.com/s/photos/sword?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In modern SW development and especially in mobile and Android, Dependency Injection is one of the most important topics out there! <br>Managing and working correctly with dependencies will make our code maintainable and testable.</p><p>DI frameworks takes care of creation and providing dependencies which allow us to focus on the important stuff of our code.</p><p>When speaking on DI in Android, Dagger and Dagger2 used to be one of the most popular DI frameworks out there, but if you know Dagger, it also required some maintenance and was accompanied with some boilerplate code just for creating the dependencies, and when we wanted to inject dependencies to Android classes like Activity and Fragments, we had to get an instance of DaggerComponent, and run an inject method from it. Or, we could use the Dagger Android extension package for making this a little bit more comfortable.</p><p>Still, many developers which I know, suffered when it comes to maintain Dagger code and many times did mistakes which caused build problems or just used it in the wrong way.</p><p>Fortunately, Google came out with a new and much more friendly DI framework which built on top of Dagger, but with less boilerplate and much easier to understand. Hilt!</p><p><strong>Hilt Building Blocks</strong></p><ul><li><strong><em>@HiltAndroidApp</em></strong> — Adds our Application to the Hilt graph</li><li><strong><em>@Component</em></strong> — A <strong>predefined</strong> containers for Android classes scopes</li><li><strong><em>@Module</em></strong> — A class, this is where we define provide/bind methods for injecting third party classes objects, or any other types which we don’t have access to their constructor like interfaces</li><li><strong><em>@AndroidEntryPoint</em></strong> — Adds Android classes to Hilt graph</li><li><strong><em>@ViewModelInject </em></strong>— Used to inject dependencies to ViewModel (say goodbye to ViewModelFactory)</li></ul><p><strong>Injection Types<br></strong>In Hilt, there are 3 ways we can provide dependencies to classes:</p><ul><li><strong>Constructor injection:</strong> Mark the class constructor with <strong><em>@Inject</em></strong> annotation</li><li><strong>Field injection:</strong> Mark a field with <strong><em>@Inject</em></strong> annotation (Basically used in Android classes like Fragment or Activity)</li><li><strong>Module Injection:</strong> Use <strong><em>@Provide</em></strong> or <strong><em>@Bind</em></strong> methods in a <strong><em>@Module</em></strong></li></ul><p><strong>Constructor Injection<br></strong>So, we’ve created some classes with some dependencies. In order to add these classes to Hilt graph, all we have to do is to mark their constructor with <strong><em>@Inject</em></strong> annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f908319b3f584b7d0b08cf931eafb46f/href">https://medium.com/media/f908319b3f584b7d0b08cf931eafb46f/href</a></iframe><p>In the above example, both the Car and Engine classes constructors marked with <strong><em>@Inject</em></strong>. Thats all, they are now both added to Hilt graph and will be available in places that needed. Thanks to the <strong><em>@Inject</em></strong> annotation, Hilt knows how to supply the Engine to the Car, and the Car will be available for uses in other places.</p><pre>Please notice that fields in constructor inject <strong><em>can be private</em></strong></pre><p><strong>Field Injection<br></strong>Usually, Field Injection required in Android classes like Fragment or Activity. The reason for that is that we don’t own these classes, and usually we don’t have access to their constructor and that their creation and lifecycle managed by the Android framework for us. <br>Suppose, we want to use the Car from the above example in an Android class like a Fragment. For this, we need to do three things:</p><ol><li>Mark our Android application with <strong><em>@HiltAndroidApp</em></strong></li><li>Mark our Fragment with <strong><em>@AndroidEntryPoint</em></strong></li><li>Mark the Car field in the Fragment with <strong><em>@Inject</em></strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f677cb62797a0203e407fd05e3d6670e/href">https://medium.com/media/f677cb62797a0203e407fd05e3d6670e/href</a></iframe><p>Thats All!! No need to use any DaggerComponent.inject() methods! <br>Thanks to the <strong><em>@HiltAndroidApp</em></strong> and <strong><em>@AndroidEntryPoint </em></strong>annotations, Hilt can inject dependencies to our Fragment! Awesome!!</p><pre>Please notice that when we mark a Fragment with <em>@AndroidEntryPoint</em>, we must mark its Activity as well!! Don&#39;t forget that! </pre><pre>Also, fields marked with <strong><em>@Inject</em></strong> must <strong><em>not be</em></strong> <strong><em>private</em></strong></pre><pre>In addition, so far, we haven&#39;t used any <strong><em>@Module</em></strong> yet, that&#39;s because we&#39;ve marked all our dependencies constructors (Car and Engine) with @Inject</pre><p><strong>ViewModel Injection<br></strong>Suppose we want to inject our Car into a ViewModel, and use this ViewModel in a Fragment. For this, we need to do two things:</p><ol><li>Mark our ViewModel constructor with <strong><em>@ViewModelInject</em></strong></li><li>Use the <strong><em>by viewModel</em></strong><em>s </em>syntax in our Fragment</li></ol><p>Check this out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42d78407296e387177e6a6b933b67f43/href">https://medium.com/media/42d78407296e387177e6a6b933b67f43/href</a></iframe><p>Thats All!! <br>As we can see, we don’t need to use <strong><em>ViewModel.Factory</em></strong> and ViewModel.Providers() anymore, Hilt will create the ViewModel with the dependency and inject it to our Fragment!</p><p><strong>Module Injection<br></strong>Most of the times, we use third party libraries like Retrofit ,OkHttpClient, SharedPreferences etc’, or, we define our dependencies as an Interface like Repository or DataSource. All above has one thing in common, we don’t have an access to their constructor for annotating them with <strong><em>@Inject</em></strong>! to provide these kind of dependencies we should use a <strong><em>@Module.</em></strong></p><p>Suppose we want to create a network client with Retrofit. Retrofit, depends on an OkHttpClient to work. Both Retrofit and OkHttpClient are third party classes. To create them, we will use a <strong>@Module.</strong></p><ol><li>Define a Module class and mark it with <strong><em>@Module</em></strong> annotation</li><li>Use the <strong><em>@InstallIn</em></strong> to tell Hilt on which <strong>predefined component</strong> it should be lived! Hilt provides us predefined components which dependencies are scoped in. To learn more about Hilt predefined components, <a href="https://developer.android.com/training/dependency-injection/hilt-android#generated-components">checkout the documentation</a></li><li>Define <strong><em>@Provide</em></strong> methods in the <strong><em>@Module</em></strong> class to create the dependencies</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d92b0a05b1aec78e006d469d806d02ae/href">https://medium.com/media/d92b0a05b1aec78e006d469d806d02ae/href</a></iframe><p>In the above example we defined a the NetworkModule class.<br>First, we’ve created a class annotated with <strong><em>@Modul</em>e</strong> which installed in the <strong>predefined</strong> <strong>ApplicationComponent</strong>, this component lives for the whole period of our app instance. Singleton objects created in this scope available for all of our app runtime.<br>Then, we defined a method to create the OkHttpClient object with all of its dependencies like interceptors etc’, this one required further down to create the Retrofit object. <br>Next, We defined another <strong><em>@Provide</em></strong> method to create Retrofit object for the rest of our app. The OkHttpClient required for creating Retrofit will be provided by Hilt thanks to the method above it. <br>Thats All! Our app Retrofit is ready to use. <br>We can now use it to create an Endpoint object, this will be done in another <strong><em>@Module</em></strong> for connivance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1112830dd39a341cc154cb2055c7772/href">https://medium.com/media/d1112830dd39a341cc154cb2055c7772/href</a></iframe><p>In the above example, we defined the Endpoints <strong><em>@Module</em></strong>, here we defined another <strong><em>@Provide</em></strong> method to create the AppEndpoint with the Retrofit object we defined in the NetworkModule. Great!! We have our network infrastructure ready! <br>We can now use it to create the rest of our architecture dependencies such as Repository and DataSources!</p><p><strong>Injecting interfaces using @Bind in a @Module <br></strong>When defining dependencies, it is highly recommended to define them as instance of an interface. This way, we depend on the interface rather on a concrete implementation. This will gives us more flexibility if we want to replace the logic in the future or supply a mock instance on testing. <br>As we know, an interface doesn’t has a constructor for us to mark it with <strong><em>@Inject</em></strong> annotation. So, in order to provide dependencies which are an instance of an interface we should use <strong><em>@Bind</em></strong> methods in a <strong><em>@Module</em></strong>.<br>If this sounds complicated, don’t worry, let see some code examples and it will be much easier to understand.</p><p>Suppose our ViewModel needs a Repository to work. <br>We will define the Repository as an interface first, and then we will create the Repository implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b8b689f28ed9e2b8d2363121471bc9/href">https://medium.com/media/a6b8b689f28ed9e2b8d2363121471bc9/href</a></iframe><p>In the above example, we’ve created the Repository interface and the RepositoryImpl class. Notice that the implementation has a dependency also, the RemoteDataSource, which is also an interface! <br>Lets see it’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9971a276a5a7f966ee8cdb9b2f8688a1/href">https://medium.com/media/9971a276a5a7f966ee8cdb9b2f8688a1/href</a></iframe><p>In the above code, we’ve defined the RemoteDataSource interface and the RemoteDataSourceImpl class. Notice that the RemoteDataSourceImpl class has the AppEndpoint dependency! <br>Now, we want to use the Repository in our ViewModel like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5ee1dcdb308023d6b0e19bfbe0a4ea2/href">https://medium.com/media/a5ee1dcdb308023d6b0e19bfbe0a4ea2/href</a></iframe><p>Although we marked the ViewModel constructor with <strong><em>@InjectViewModel </em></strong>as we should, Hilt cannot tell how to provide the Repository instance because it’s an interface. <br>Also, it cannot tell how to provide the RemoteDataSource to the Repository implementation as it also, an interface. <br>To add Hilt all of these we should do the following:</p><ol><li>Mark the Impl classes constructor with <strong><em>@Inject</em></strong></li><li>Define <strong><em>@Bind</em></strong> methods for the implementations in a <strong><em>@Module</em></strong></li></ol><p>As said, first, lets mark the implementation classes (RemoteDataSourceImpl and RepositoryImpl) constructors with <strong><em>@Inject</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef7e24ab1c7e384005c5dafac4f27754/href">https://medium.com/media/ef7e24ab1c7e384005c5dafac4f27754/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27f5369c8b04937c2932988a509ba678/href">https://medium.com/media/27f5369c8b04937c2932988a509ba678/href</a></iframe><p>Done! Notice that we already defined the AppEndpoint dependency in the EndpointModule class, this is how Hilt will know how to supply it to the RemoteDataSourceImpl class.</p><p>We still need to create another <strong><em>@Module</em></strong> with <strong><em>@Bind</em></strong> methods to provide the RepositoryImpl and RemoteDataSourceImpl classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f89053103f9e3cbff95351809416204/href">https://medium.com/media/3f89053103f9e3cbff95351809416204/href</a></iframe><p>In the above code snippet, we’ve created a new <strong><em>@Module</em></strong> and define two <strong><em>@Bind</em></strong> methods signatures with a single parameter. <strong>The method returns type is the interface type</strong>, <strong>while the parameter type is the implementation!!</strong> <br>Notice, that the <strong><em>@Bind</em></strong> methods are abstract, this is required. Due to that, we should make the whole <strong><em>@Module</em></strong> class abstract as well.</p><p>Thats All!! Hilt now has all what it needs to provide interfaces implementations to our ViewModel, thanks to the @Bind methods and our Hilt graph is now ready for work!</p><p><strong>Using Qualifiers for multiple instances of the same type<br></strong>Many times, we need to provide different instances of same type in different places. <br>For example, we want to have two OkHttpClients with different configuration. <br>Check out this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4718ad70473c02b579de81703699e109/href">https://medium.com/media/4718ad70473c02b579de81703699e109/href</a></iframe><p>In the code above, we create 2 network adapters with 2 OkHttpClients. One with interceptor and another one without. Notice that both of the Retrofit provide methods requires OkHttpClient, so how we can distinguish between the two of them? <br>For this, we should define Qualifiers and use them in the @Module class.</p><p><strong>Define Qualifiers for OkHttpClient</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee43234e59dfae3a4b8f568c2c5cd43b/href">https://medium.com/media/ee43234e59dfae3a4b8f568c2c5cd43b/href</a></iframe><p>In the above code snippet, we’ve defined 2 Qualifiers for both auth and none auth OkHttpClient. Now we can use these Qualifiers in our Module to distinguish between the 2 OkHttpClients objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e4023c273b1c5e52dce72ac7a72d70/href">https://medium.com/media/91e4023c273b1c5e52dce72ac7a72d70/href</a></iframe><p>Great!! Qualifiers gives us the power to inject any type which has different instances easily!!</p><p><strong>Having <em>@Bind</em> and <em>@Provide</em> methods in the same <em>@Module</em></strong><br>There one important thing I like to point out here regarding the <strong>abstract</strong> @Bind methods in an abstract @Module. As I mentioned in the above sections, <em>@Provide</em> methods and <em>@Bind </em>methods defined in a <em>@Module</em> class, but <em>@Bind</em> methods are abstract and <em>@Provide</em> methods aren’t. As a result, when we want to use <em>@Bind</em> methods we must make our <em>@Module</em> class abstract as well. This causes a little problem as we cannot have both abstract and non-abstract methods in an abstract <em>@Module</em> class.</p><p>However, there is a solution for this situation. Simply, by making our <em>@Provide</em> methods <strong>static </strong>(in Kotlin we use the companion object)<strong> </strong>we can have both <em>@Bind</em> and <em>@Provide</em> methods in the same module.</p><p>Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bb342a898de946e8392d8b1c0662238/href">https://medium.com/media/2bb342a898de946e8392d8b1c0662238/href</a></iframe><p>In the example above, we can see how having both @Bind and @Provide methods in the same abstract @Module</p><p><strong>Summary<br></strong>As I am already using hilt in my Android app for a few weeks, I’ve found it highly simpler than Dagger! it makes my project cleaner and much more maintainable than ever! Hilt provides much more options and capabilities when it comes to scope objects in the lifecycle of our app, you can read about all the options in the details <a href="https://developer.android.com/training/dependency-injection/hilt-android">documentation</a>:<br>In addition, I encourage you to go over the Hilt <a href="https://codelabs.developers.google.com/codelabs/android-hilt#0">CodeLab</a> which will give you first HandsOn experience and also will give you a little taste of to work with Hilt and testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=470f0963dca7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/say-goodbye-to-dagger-hello-hilt-470f0963dca7">Say Goodbye to Dagger, Hello Hilt</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>