<?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 Tonyo Francis on Medium]]></title>
        <description><![CDATA[Stories by Tonyo Francis on Medium]]></description>
        <link>https://medium.com/@tonyofrancis?source=rss-d65af34e9895------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mdtvlC58Xxv3HS00LTkGhg.jpeg</url>
            <title>Stories by Tonyo Francis on Medium</title>
            <link>https://medium.com/@tonyofrancis?source=rss-d65af34e9895------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:15:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonyofrancis/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[Dispatch: A simple work scheduler for Android]]></title>
            <link>https://medium.com/@tonyofrancis/dispatch-a-simple-work-scheduler-for-android-887b5f75c671?source=rss-d65af34e9895------2</link>
            <guid isPermaLink="false">https://medium.com/p/887b5f75c671</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Tonyo Francis]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 20:56:27 GMT</pubDate>
            <atom:updated>2019-04-30T20:56:27.347Z</atom:updated>
            <content:encoded><![CDATA[<p>Dispatch is a simple and flexible work scheduler that schedulers work on a background or UI thread in the form of a dispatch queue.</p><pre>Dispatcher.<strong>backgroundDispatchQueue<br>    </strong>.async <strong>{<br>        </strong><em>//do background work here<br>        </em><strong>val </strong>sb = StringBuilder()<br>        <strong>for </strong>(i <strong>in </strong>0..100) {<br>            sb.append(i)<br>              .append(<strong>&quot; &quot;</strong>)<br>        }<br>        sb.toString()<br>    <strong>}<br>    </strong>.post <strong>{ </strong>data <strong>-&gt;<br>        </strong><em>//do ui work here<br>        print</em>ln(data)<br>    <strong>}<br>    </strong>.start()</pre><p>Dispatch makes it very clear which thread your code is running on. Like what you see? Read on!</p><p>One of the many problems with offloading work to a background thread on Android, is knowing the right time to cancel the work when it is no longer needed. Dispatch makes it very easy to cancel a dispatch queue. Simply call the cancel() method on the queue. If that is not good enough, allow your Activity’s life cycle to manage this for you.</p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        Dispatcher.<strong>networkDispatchQueue</strong><em><br>            </em>.managedBy(<strong>this</strong>)<br>            .async <strong>{<br>                </strong><em>//do work in background<br>            </em><strong>}<br>            </strong>.post <strong>{<br>                </strong><em>//handle results on ui<br>            </em><strong>}<br>            </strong>.start()<br>    }<br><br>}</pre><p>In the above example, the queue is managed by the Activity’s life cycle, and it will be cancelled when the Activity is destroyed. What if you want to control the cancellation of the queue when the Activity pauses or stops? Sure you can! Like so:</p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br>    <br>    <strong>override fun </strong>onResume() {<br>        <strong>super</strong>.onResume()<br>        Dispatcher.<strong>networkDispatchQueue<br>            </strong>.managedBy(<strong>this</strong>, CancelType.<strong>PAUSED</strong>)<br>            .async <strong>{<br>                </strong><em>//do work in background<br>            </em><strong>}<br>            </strong>.post <strong>{<br>                </strong><em>//handle results on ui<br>            </em><strong>}<br>            </strong>.start()<br>    }<br><br>}</pre><p>In this example, the queue is canceled when the Activity’s onPause method is called. There is no need to store the queue in a variable and cancel in manually in a callback method. You can if you want. The choice is yours.</p><p>Dispatch uses a DispatchQueueController to manage when a queue is canceled. There are many variations of the DispatchQueueController : LifecycleDispatchQueueController and ActivityDispatchQueueController. You can extend any of those classes to create your own queue controllers and set them on a queue.</p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br><br>    <strong>private val dispatchQueueController </strong>= DispatchQueueController()<br>    <br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        Dispatcher.<strong>networkDispatchQueue<br>            </strong>.managedBy(<strong>dispatchQueueController</strong>)<br>            .async <strong>{<br>                </strong><em>//do work in background<br>            </em><strong>}<br>            </strong>.post <strong>{<br>                </strong><em>//handle results on ui<br>            </em><strong>}<br>            </strong>.start()<br>    }<br><br>    <strong>override fun </strong>onDestroy() {<br>        <strong>super</strong>.onDestroy()<br>        <strong>dispatchQueueController</strong>.cancelAllDispatch()<br>    }<br><br>}</pre><p>Managing queues could not be easier.</p><h4>Queue Types</h4><p>Dispatch comes with many pre-exiting queues:</p><pre>Dispatcher.<strong>backgroundDispatchQueue<br> <br></strong>Dispatcher.<strong>ioDispatchQueue<br> <br></strong>Dispatcher.<strong>networkDispatchQueue<br><br></strong>Dispatcher.<strong>backgroundSecondaryDispatchQueue</strong></pre><p>These queues are generated only when you need/access them. You can also create you own dispatch queues via the many create methods on the Dispatcher object.</p><pre>Dispatcher.createDispatchQueue()<br><br>Dispatcher.createDispatchQueue(ThreadType.<strong>NEW</strong>)<br><br>Dispatcher.createIntervalDispatchQueue(delayInMillis = 1_000)<br><br>Dispatcher.createTimerDispatchQueue(delayInMillis = 10_000)</pre><p>These are just some of the queues you can create.</p><h4><strong>Network Queues with Retrofit</strong></h4><p>We all know and love the <a href="https://square.github.io/retrofit/">Retrofit</a> library created by the wonderful people at <a href="https://squareup.com/us/en">Square</a>. Dispatch works seamlessly with your Retrofit code! Let’s walkthrough a simple service example.</p><p><em>TestJsonData.kt</em></p><pre><strong>class </strong>TestJsonData {<br><br>    <strong>var id</strong>: Int = 0<br><br>    <strong>var nm</strong>: String = <strong>&quot;&quot;<br><br>    var cty</strong>: String = <strong>&quot;&quot;<br><br>    override fun </strong>toString(): String {<br>        <strong>return &quot;TestJsonData(id=$id, nm=&#39;$nm&#39;, cty=&#39;$cty&#39;)&quot;<br>    </strong>}<br><br>}</pre><p><em>TestService.kt</em></p><pre><strong>interface </strong>TestService {<br><br>    @GET(<strong>&quot;/api/data?list=englishmonarchs&amp;format=json&quot;</strong>)<br>    <strong>fun </strong>getSampleJson(): Dispatch&lt;List&lt;TestJsonData&gt;&gt;<br><br>}</pre><p><em>SimpleActivity.kt</em></p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br><br>    <strong>private lateinit var retrofit</strong>: Retrofit<br>    <strong>private lateinit var service</strong>: TestService<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br><br>        <strong>val </strong>dispatchCallAdapterFactory = DispatchCallAdapterFactory.create()<br>        <br>        <strong>retrofit </strong>= Retrofit.Builder()<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .addCallAdapterFactory(dispatchCallAdapterFactory)<br>            .baseUrl(<strong>&quot;http://mysafeinfo.com&quot;</strong>)<br>            .build()<br>        <strong>service </strong>= <strong>retrofit</strong>.create(TestService::<strong>class</strong>.<em>java</em>)<br><br>        runTestService()<br>    }<br><br>    <strong>private fun </strong>runTestService() {<br>        <strong>service</strong>.getSampleJson()<br>            .managedBy(<strong>this</strong>)<br>            .post <strong>{ </strong>data <strong>-&gt;<br>                for </strong>(testJsonData <strong>in </strong>data) {<br>                    <em>println</em>(testJsonData)<br>                }<br>            <strong>}<br>            </strong>.start()<br>    }<br><br>}</pre><p>See how super easy it is to integrate Dispatch with Retrofit? All you need is a DispatchCallAdapterFactory instance, and set your Service methods to return the data wrapped in a Dispatch object.</p><h4>Zipping Queues</h4><p>There will be times when you would like to join the results of two or more queues. Call the zip methods to do this.</p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br><br>    <strong>private val lifecycleDispatchQueueController </strong>= LifecycleDispatchQueueController()<br><br>    <strong>override fun </strong>onResume() {<br>        <strong>super</strong>.onResume()<br>        Dispatcher.<strong>backgroundDispatchQueue<br>            </strong>.managedBy(<strong>lifecycleDispatchQueueController</strong>, CancelType.<strong>PAUSED</strong>)<br>            .async <strong>{<br>                </strong><em>mapOf</em>(0 <em>to </em><strong>&quot;cat&quot;</strong>, 1 <em>to </em><strong>&quot;bat&quot;</strong>)<br>            <strong>}<br>            </strong>.zipWith(getDataDispatch()) <em>// combine two queue results<br>            </em>.async <strong>{ </strong>results <strong>-&gt;<br>                for </strong>((key, value) <strong>in </strong>results.<strong>first</strong>) {<br>                    <em>println</em>(<strong>&quot;$</strong>key<strong>:$</strong>value<strong>&quot;</strong>)<br>                }<br>                <strong>for </strong>(string <strong>in </strong>results.<strong>second</strong>) {<br>                    <em>println</em>(string)<br>                }<br>            <strong>}<br>            </strong>.start()<br>    }<br><br>    <strong>private fun </strong>getDataDispatch(): Dispatch&lt;List&lt;String&gt;&gt; {<br>        <strong>return </strong>Dispatcher.<strong>backgroundDispatchQueue<br>            </strong>.async <strong>{<br>                </strong><em>listOf</em>(<strong>&quot;hat&quot;</strong>, <strong>&quot;sat&quot;</strong>)<br>            <strong>}<br>    </strong>}<br><br>    <strong>override fun </strong>onPause() {<br>        <strong>super</strong>.onPause()<br>        <strong>lifecycleDispatchQueueController</strong>.cancelAllPaused()<br>    }<br><br>}</pre><h4>Handling Errors</h4><p>Dispatch allows you to handles errors in many ways. One way is setting an error handler for the queue by passing it to the start method.</p><pre>Dispatcher.createDispatchQueue()<br>    .async <strong>{<br>        </strong><em>//do work<br>        </em><strong>val </strong>number = 66<br>        <strong>throw </strong>Exception(<strong>&quot;silly exception&quot;</strong>)<br>        number<br>    <strong>}<br>    </strong>.post <strong>{ </strong>number <strong>-&gt; <br>        </strong><em>println</em>(<strong>&quot;number is $</strong>number<strong>&quot;</strong>)<br>    <strong>}<br>    </strong>.start <strong>{ </strong>throwable, dispatch <strong>-&gt;<br>        </strong><em>//handle queue error here.<br>        </em>Log.e(<strong>&quot;errorTest&quot;</strong>,<br>            <strong>&quot;queue with id ${</strong>dispatch.<strong>queueId} throw error:&quot;</strong>, throwable)<br>    <strong>}</strong></pre><p>Note in this example the post block is never executed. It can’t because the async block was not able to provide it with the data need. So the queue calls the error handler and then cancels.</p><p>Another way to handle errors more elegantly, is to provide a doOnError block that can return a default or valid data for the preceding async or post block and allowing the execution of the following async or post blocks.</p><pre>Dispatcher.createDispatchQueue()<br>    .async <strong>{<br>        </strong><em>//do work<br>        </em><strong>val </strong>number = 66<br>        <strong>throw </strong>Exception(<strong>&quot;silly exception&quot;</strong>)<br>        number<br>    <strong>}<br>    </strong>.doOnError <strong>{ </strong>throwable <strong>-&gt; <br>        if </strong>(throwable.<strong>message </strong>== <strong>&quot;silly exception&quot;</strong>) {<br>            100<br>        } <strong>else </strong>{<br>            0<br>        }<br>    <strong>}<br>    </strong>.post <strong>{ </strong>number <strong>-&gt;<br>        </strong><em>println</em>(<strong>&quot;number is $</strong>number<strong>&quot;</strong>)<br>    <strong>}<br>    </strong>.start()</pre><p>In the above example, the doOnError block handles the exception for the preceding async block allowing the post block to be called and the queue terminates normally. It is always good practice to provide a queue with an error handler via the start method to handle errors that were not caught in the doOnError blocks.</p><p>If an error handler is not provided for the queue, the exception will be thrown causing the application to crash. To prevent this, the library allows you to provide a global error handler that will catch all exceptions thrown when using any dispatch queue. It is best practice to handle errors locally close to the location where they originated. Set the global error handler like this:</p><pre>Dispatcher.setGlobalErrorHandler <strong>{ </strong>throwable, dispatch <strong>-&gt; <br>    //handle errors<br>}</strong></pre><h4>Debugging</h4><p>Figuring out where an error occurred is not always easy. This is one of the areas Dispatch shines. Dispatch allows you to set the id for each post and async block via the setDispatchId(stringId) method. When an error does occur, the error handler provides the dispatch in which the error occurred. With this information, you can check the dispatch id and know exactly where the issue occurred. The following example shows how this is done.</p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        Dispatcher.<strong>backgroundDispatchQueue<br>            </strong>.managedBy(<strong>this</strong>)<br>            .async <strong>{<br>                </strong><em>//do work<br>                </em><strong>val </strong>number = 66<br>                <strong>throw </strong>Exception(<strong>&quot;silly exception&quot;</strong>)<br>                number<br>            <strong>}<br>            </strong>.setDispatchId(<strong>&quot;numberAsync&quot;</strong>)<br>            .post <strong>{ </strong>number <strong>-&gt;<br>                </strong><em>println</em>(<strong>&quot;number is $</strong>number<strong>&quot;</strong>)<br>            <strong>}<br>            </strong>.setDispatchId(<strong>&quot;printAsync&quot;</strong>)<br>            .start <strong>{ </strong>throwable, dispatch <strong>-&gt;<br>                if </strong>(dispatch.<strong>dispatchId </strong>== <strong>&quot;numberAsync&quot;</strong>) {<br>                    <em>//error occurred in first async block.<br>                </em>}<br>            <strong>}<br>    </strong>}<br><br>}</pre><p>You can also enable logging in the library. This will warm you when you forget to manage a queue with a DispatchQueueController .</p><pre>Dispatcher.setEnableLogWarnings(<strong>true</strong>)</pre><h4>Dispatch Observers</h4><p><em>Hey kids! Here! Have more ice-cream!</em></p><p>Dispatch does not stop at solving threading problems. Introducing DispatchObserver! Every now and then you would like a callback from the dispatch that returns a result without it being directly available. That’s where DispatchObservers come into play. You can attach a DispatchObserver to a dispatch object and get a callback when the return value is available.</p><pre><strong>class </strong>SimpleActivity: AppCompatActivity() {<br><br>    <strong>private var n </strong>= 0<br><br>    <strong>private val dispatchObserver </strong>= <strong>object</strong>: DispatchObserver&lt;Int&gt; {<br>        <strong>override fun </strong>onChanged(data: Int) {<br>            <em>print</em>(<strong>&quot;Factorial of $n is: $</strong>data<strong>&quot;</strong>)<br>        }<br>    }<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        <strong>n </strong>= 16<br><br>        Dispatcher.<strong>backgroundDispatchQueue<br>            </strong>.managedBy(<strong>this</strong>)<br>            .async <strong>{<br>                </strong>factorial(<strong>n</strong>)<br>            <strong>}<br>            </strong>.addObserver(<strong>dispatchObserver</strong>)<br>            .start()<br>    }<br><br>    <strong>private fun </strong>factorial(n: Int): Int {<br>        <strong>if </strong>(n == 0) <strong>return </strong>1<br>        <strong>return </strong>n * factorial(n - 1)<br>    }<br><br>}</pre><h4>Delays</h4><p>Both the async and post methods allow you to specify a delay in milliseconds before the block is executed.</p><pre>Dispatcher.<strong>backgroundDispatchQueue<br>    </strong>.post(5000) <strong>{<br>        </strong><em>//will be called after a 5 second delay<br>    </em><strong>}</strong>.start()</pre><h4>Android Handlers</h4><p>Sometimes you would like to dictate the thread that Dispatch uses to process blocks in the background. The library allows you to do so by providing your own Android Handlers.</p><pre><strong>val </strong>handlerThread = HandlerThread(<strong>&quot;myThread&quot;</strong>)<br>    handlerThread.start()<br><strong>val </strong>handler = Handler(handlerThread.<em>looper</em>)<br><br>Dispatcher.createDispatchQueue(handler)<br>    .async <strong>{ <br>        </strong><em>//do work on my own thread<br>    </em><strong>}<br>    </strong>.start()</pre><h4>Understanding how Dispatch Works</h4><p>Now that you have seen many of library’s features, it is time to give you a short summary about how it really works. You can skip this section and head to the following section on how to add Dispatch to your Android projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*C8xQEB-0U35MbDQ1W6Pq5g.png" /><figcaption>Simple Dispatch Queue Diagram</figcaption></figure><p>The above is a simple diagram on how a dispatch queue works. When you create a queue it returns a dispatch object. The dispatch object is responsible for the thread it performs its work on, performing the work, and returning the results. The async, post and map blocks each create a new dispatch object and adds it to the dispatch queue when called. Hence the reason you are able to chain dispatch objects and pass along their results to the next dispatch block in the queue. The overhead for creating dispatch objects are minimal. Each dispatch object can have its own onDoError handler block and manage its own DispatchObservers.</p><p><strong>Note: </strong>By default, once a Dispatch queue has completed its work, it is then cancelled and cannot be reused. To prevent a queue from cancelling automatically, call the cancelOnComplete(false) method and pass in false.</p><h4>Using Dispatch</h4><p>To use the Dispatch library in your Android project, add the following code to your project’s build.gradle file.</p><pre>implementation &quot;com.tonyodev.dispatch:dispatch:1.1.0&quot;</pre><p>To use Dispatch with Retrofit, add:</p><pre>implementation &quot;com.tonyodev.dispatch:dispatch-retrofit2-adapter:1.1.0&quot;</pre><p>View the project on <a href="https://github.com/tonyofrancis/Dispatcher">GitHub</a>. Hope you enjoyed reading this post. Until next time. Happy Dispatching!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=887b5f75c671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Fetch, a better file downloader library for Android.]]></title>
            <link>https://medium.com/@tonyofrancis/introducing-fetch-a-download-manager-library-for-android-1ecc379faa6c?source=rss-d65af34e9895------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ecc379faa6c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-tutorials]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Tonyo Francis]]></dc:creator>
            <pubDate>Wed, 03 Jan 2018 21:44:56 GMT</pubDate>
            <atom:updated>2018-03-07T00:19:14.119Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been working on the Fetch library for quite some time now, and very excited to announce its second major release which I am calling “Fetch2”. The goals for creating this new version were very clear.</p><ol><li>Fetch had to be rebuilt with the Kotlin language.</li><li>The library has to use very little system resources.</li><li>Fetch has to be flexible and customizable.</li><li>Faster downloading and accurate progress and status reporting.</li></ol><h4>What is Fetch?</h4><p>Fetch is a simple, powerful, customizable file download manager library for Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*8Th5wtvkBUwiWu4E6BBwLA.png" /><figcaption>Screenshot from Fetch sample app.</figcaption></figure><h4>Features</h4><ul><li>Simple and easy to use API.</li><li>Continuous downloading in the background.</li><li>Concurrent downloading support.</li><li>Ability to pause and resume downloads.</li><li>Set priority on downloads.</li><li>Network specific downloading support.</li><li>Download remaining time reporting.</li><li>And more…</li></ul><h4>How to use Fetch?</h4><p>Using Fetch is easy! Just add the Gradle dependency to your application’s build.gradle file.</p><pre>implementation &quot;com.tonyodev.fetch2:fetch2:2.0.0-RC9&quot;</pre><p>Next, get an instance of Fetch using the builder, and request a download.</p><pre>public class MainActivity extends AppCompatActivity {</pre><pre>private Fetch mainFetch;</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);</pre><pre>mainFetch = new Fetch.Builder(context, &quot;Main&quot;)<br>                  .setDownloadConcurrentLimit(4) // Allows Fetch to download 4 downloads in Parallel.<br>                  .enableLogging(true)<br>                  .build();</pre><pre>//Single enqueuing example            <br>        final Request request = new Request(url, file);<br>        request.setPriority(Priority.HIGH);<br>        request.setNetworkType(NetworkType.WIFI_ONLY);<br>        request.addHeader(&quot;clientKey&quot;, &quot;SD78DF93_3947&amp;MVNGHE1WONG&quot;);</pre><pre>mainFetch.enqueue(request, new Func&lt;Download&gt;() {<br>               <a href="http://twitter.com/Override">@Override</a><br>               public void call(Download download) {<br>                   //Request successfully Queued for download<br>               }<br>           }, new Func&lt;Error&gt;() {<br>               <a href="http://twitter.com/Override">@Override</a><br>               public void call(Error error) {<br>                   //An error occurred when enqueuing a request.<br>               }<br>           });</pre><pre>// Multi enqueuing example with group id   <br>        final List&lt;Request&gt; requestList = getSampleRequests();<br>        final int groupId = &quot;MySampleGroup&quot;.hashCode();<br>        for(int i = 0; i &lt; requestList.size(); i++) {<br>            requestList.get(i).setGroupId(groupId);<br>        }</pre><pre>mainFetch.enqueue(requestList, new Func&lt;List&lt;? extends Download&gt;&gt;() {<br>            <a href="http://twitter.com/Override">@Override</a><br>            public void call(List&lt;? extends Download&gt; downloads) {<br>                //Successfully enqueued requests.<br>            }<br>        }, new Func&lt;Error&gt;() {<br>            <a href="http://twitter.com/Override">@Override</a><br>            public void call(Error error) {<br>                // An error occurred when enqueuing requests.<br>            }<br>        });<br>}</pre><p>Tracking a download’s progress and status is very easy with Fetch. Simply add a FetchListener to your Fetch instance, and the listener will be notified whenever a download’s status or progress changes.</p><pre>fetch.addListener(new FetchListener() {<br>    <a href="http://twitter.com/Override">@Override</a><br>    public void onQueued(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {<br>        if (request.getId() == download.getId()) {<br>            showDownloadInList(download);<br>        }<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onCompleted(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onError(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onProgress(<a href="http://twitter.com/NotNull">@NotNull</a> Download download, long etaInMilliSeconds) {<br>      if (request.getId() == download.getId()) {<br>          updateDownload(download, etaInMilliSeconds);<br>      }<br>      final int progress = download.getProgress();<br>      Log.d(&quot;Fetch&quot;, &quot;Progress Completed :&quot; + progress);<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onPaused(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onResumed(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onCancelled(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onRemoved(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onDeleted(<a href="http://twitter.com/NotNull">@NotNull</a> Download download) {</pre><pre>}<br>});</pre><p>Fetch supports pausing and resuming downloads using the request’s id.<br>A request’s id is a unique identifier that maps a request to a Fetch Download.<br>A download returned by Fetch will have have an id that matches the request id that started the download.</p><pre>final Request request1 = new Request(url, file);<br>final Request request2 = new Request(url2, file2);</pre><pre>fetch.pause(request.getId());</pre><pre>...</pre><pre>fetch.resume(request2.getId());</pre><pre>...</pre><pre>//You can also pause and resume downloads using the group id the download belongs to.<br>int groupId = &quot;AGroup&quot;.hashCode();<br>fetch.pauseGroup(groupId);<br>fetch.resumeGroup(groupId);</pre><p>You can query Fetch for download information in several ways.</p><pre>//Query all downloads<br>fetch.getDownloads(new Func&lt;List&lt;? extends Download&gt;&gt;() {<br> <a href="http://twitter.com/Override">@Override</a><br>        public void call(List&lt;? extends Download&gt; downloads) {<br>         //Access all downloads here<br>        }<br>});</pre><pre>//Get all downloads with a status<br>fetch.getDownloadsWithStatus(Status.DOWNLOADING, new Func&lt;List&lt;? extends Download&gt;&gt;() {<br> <a href="http://twitter.com/Override">@Override</a><br>        public void call(List&lt;? extends Download&gt; downloads) {<br>         //Access downloads that are downloading<br>        }<br>});</pre><pre>// You can also access grouped downloads<br>final int groupId = 52687447745;<br>fetch.getDownloadsInGroup(groupId, new Func&lt;List&lt;? extends Download&gt;&gt;() {<br> <a href="http://twitter.com/Override">@Override</a><br>   public void call(List&lt;? extends Download&gt; downloads) {<br>        //Access grouped downloads<br>   }<br>});When you are done with an instance of Fetch, simply release it.</pre><pre>//do work</pre><pre>fetch.close();</pre><pre>//do more work</pre><h4>Downloaders</h4><p>By default Fetch uses the HttpUrlConnection client via the HttpUrlConnectionDownloader to download requests. Add the following Gradle dependency to your application’s build.gradle to use the OkHttp Downloader instead. You can create your own custom downloaders<br>if necessary. See the Java docs for details.</p><pre>implementation &quot;com.tonyodev.fetch2downloaders:fetch2downloaders:2.0.0-RC9&quot;</pre><p>Set the OkHttp Downloader for Fetch to use.</p><pre>final OkHttpClient okHttpClient = new OkHttpClient.Builder()<br>          .build();</pre><pre>final Fetch fetch = new Fetch.Builder(context, &quot;Main&quot;)<br> .setDownloader(new OkHttpDownloader(okHttpClient))<br>        .setDownloadConcurrentLimit(4) // Allows Fetch to download 4 downloads in Parallel.<br>        .enableLogging(true)<br>        .build();</pre><h4>RxFetch</h4><p>If you would like to take advantage of RxJava2 features when using Fetch,<br>add the following gradle dependency to your application’s build.gradle file.</p><pre>implementation “com.tonyodev.fetch2rx:fetch2rx:2.0.0-RC9”</pre><p>RxFetch makes it super easy to enqueue download requests and query downloads using rxJava2 functional methods.</p><pre>final RxFetch rxFetch = new RxFetch.Builder(context, &quot;Main&quot;)<br>  .setDownloadConcurrentLimit(2)<br>  .enableLogging(true)<br>  .build();</pre><pre>rxFetch.getDownloads()<br>        .asFlowable()<br>        .subscribe(new Consumer&lt;List&lt;Download&gt;&gt;() {<br>            <a href="http://twitter.com/Override">@Override</a><br>            public void accept(List&lt;Download&gt; downloads) throws Exception {<br>                //Access results<br>            }<br>        }, new Consumer&lt;Throwable&gt;() {<br>            <a href="http://twitter.com/Override">@Override</a><br>            public void accept(Throwable throwable) throws Exception {<br>                //An error occurred<br>                final Error error = FetchErrorUtils.getErrorFromThrowable(throwable);<br>            }<br>        });</pre><p>Migrate downloads from Fetch1 to Fetch2 using the migration assistant. Add the following gradle dependency to your application’s build.gradle file.</p><pre>implementation &quot;com.tonyodev.fetchmigrator:fetchmigrator:2.0.0-RC9&quot;</pre><p>Then run the Migrator.</p><pre>try {<br>    final String fetch2Namespace = &quot;Main&quot;;<br>    FetchMigrator.migrateFromV1toV2(this, fetch2Namespace);<br>    FetchMigrator.deleteFetchV1Database(this);</pre><pre>final Fetch fetch = new Fetch.Builder(context, fetch2Namespace)<br>      .setDownloadConcurrentLimit(4) // Allows Fetch to download 4 downloads in Parallel.<br>      .enableLogging(true)<br>      .build();</pre><pre>fetch.getDownloads(new Func&lt;List&lt;? extends Download&gt;&gt;() {<br>        <a href="http://twitter.com/Override">@Override</a><br>        public void call(List&lt;? extends Download&gt; downloads) {<br>            /* All downloads from the first version of Fetch<br>             * will now be maintained, downloaded and monitored in version 2 of Fetch.<br>            */<br>        }<br>    });<br>} catch (SQLException e) {<br>    e.printStackTrace();<br>}</pre><p>Now that you have seen the how <em>simple, easy, powerful and customizable</em> Fetch is, head over to <a href="https://github.com/tonyofrancis/fetch">GitHub</a> to download the sample project. Happy Downloading!</p><p>Update: Updated library version number to latest version with many fixes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ecc379faa6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetch]]></title>
            <link>https://medium.com/@tonyofrancis/fetch-d61ca0e718c8?source=rss-d65af34e9895------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61ca0e718c8</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[androidarsenal]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Tonyo Francis]]></dc:creator>
            <pubDate>Wed, 01 Feb 2017 23:45:40 GMT</pubDate>
            <atom:updated>2017-02-01T23:45:40.546Z</atom:updated>
            <content:encoded><![CDATA[<p>A better in app Download Manager for Android.</p><h3>Overview</h3><p>Fetch is a simple yet powerful Android library that allows you to manage downloads more efficiently in your Android apps. It uses a background service on the device to download and maintain requests.</p><h3>Features</h3><ul><li>Simple and easy to use API.</li><li>Continuous downloading in the background.</li><li>Ability to pause and resume downloads.</li><li>Set the priority of a download request.</li><li>Ability to retry failed downloads.</li><li>Easy progress and status tracking.</li><li>And more…</li></ul><h3>How to use Fetch</h3><h4>Prerequisites</h4><p>If you are saving downloads outside of your application’s sandbox, you will need to add the following storage permissions to your application’s manifest. For Android SDK version 23(M) and above, you will also need to explicitly request these permissions from the user.</p><pre>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;/&gt;</pre><pre>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot;/&gt;</pre><h4>Let’s begin!</h4><p>Using Fetch is easy! Just add the Gradle dependency to your application’s build.gradle file.</p><pre>compile &#39;com.tonyodev.fetch:fetch:1.0.0&#39;</pre><p>Next, get an instance of Fetch and request a download. A unique ID will be returned for each request.</p><pre>public class MainActivity extends AppCompatActivity {</pre><pre>    @Override<br>    public void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);</pre><pre>        Fetch fetch = Fetch.getInstance(this);</pre><pre>        ...</pre><pre>        Request request = new Request(url,filePath);<br>        long downloadId = fetch.enqueue(request);        <br>    }</pre><pre>}</pre><p>Tracking a download’s progress and status is very easy with Fetch. Simply add a FetchListener to your instance, and the listener will be notified whenever a download’s status or progress changes.</p><pre>fetch.addFetchListener(new FetchListener() {</pre><pre>    @Override<br>    public void onUpdate(long id, int status, int progress, int error) {</pre><pre>        if(downloadId == id) {</pre><pre>            progressBar.setProgress(progress);<br>            ...<br>        }<br>    }     <br>});</pre><p>Fetch supports pausing and resuming downloads. If a download request fails, you can opt to retry.</p><pre>...</pre><pre>fetch.pause(downloadId);</pre><pre>...</pre><pre>fetch.resume(downloadId);</pre><pre>...</pre><pre>fetch.retry(downloadId);</pre><p>When you are done with an instance of Fetch, simply release it. <strong>It is important that you release instances of fetch to prevent memory leaks.</strong></p><pre>//do work</pre><pre>fetch.release();</pre><pre>//do more work</pre><p>That’s it! you’re done. Fetch is very simple and easy to use. Visit the Github repository <a href="https://github.com/tonyofrancis/Fetch">here</a>.</p><p>I would love to hear your feedback on using the Fetch Library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61ca0e718c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>