<?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 SumOn Hasan on Medium]]></title>
        <description><![CDATA[Stories by SumOn Hasan on Medium]]></description>
        <link>https://medium.com/@sumonedium?source=rss-dec8e10d5f24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5fmTUaiRN4NCQ0E9</url>
            <title>Stories by SumOn Hasan on Medium</title>
            <link>https://medium.com/@sumonedium?source=rss-dec8e10d5f24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:47:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumonedium/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[Kotlin : Scope Functions & Their use]]></title>
            <link>https://medium.com/@sumonedium/kotlin-scope-functions-their-use-d3a5fabbeec2?source=rss-dec8e10d5f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3a5fabbeec2</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-scope-functions]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[SumOn Hasan]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 04:09:58 GMT</pubDate>
            <atom:updated>2021-11-29T04:14:12.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin : Scope Functions &amp; Their uses</h3><h4>Don’t abuse Kotlin’s scope functions</h4><p>The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a <a href="https://kotlinlang.org/docs/lambdas.html">lambda expression</a> provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called <em>scope functions</em>. There are five of them: let, run, with, apply, and also</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf_NacADWc_RWQFH6_eYWg.jpeg" /></figure><h3>Object References</h3><p>To use these functions, we must understand a couple of things.</p><p>Inside a lambda of a scope function, <strong><em>this</em> </strong>(lambda receiver) is used to access the context object. The same object can be accessed by using <strong><em>it</em> </strong>(lambda argument). In general, both can perform similar things.</p><h3>This</h3><p>Inside a scope function, you will be able to reference the context object by a short word (<strong><em>this</em></strong>), instead of the name itself.</p><p><strong>run</strong>, <strong>apply</strong>, <strong>with </strong>use ‘<strong><em>this</em></strong>’ to access the context object.</p><p><strong>Note</strong>: We can exclude this keyword to refer to members of the class.</p><pre>fun main() {<br>    var user = User(&quot;Joe&quot;,&quot;London&quot;)<br>    val username = with(user) {<br>        name = &quot;Palani&quot;<br>        address = &quot;India&quot;<br>        println(&quot;Name = $name , Address = $address&quot;)<br>        name<br>    }<br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>It</h3><p>‘<strong>let</strong>’ and ‘<strong>also</strong>’ functions refer to the object’s context as a lambda argument.</p><pre>fun main() {<br>    var user = User(&quot;Joe&quot;,&quot;London&quot;)<br>    user.let {<br>        println(&quot;Name : ${it.name}&quot;)<br>        println(&quot;Address : ${it.address}&quot;)<br>    }<br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>Return values</h3><p>There are two types of return values that a scope function can return:</p><h3>Lambda result</h3><p>If we write any expression at the end of the code block, it becomes the return value for the scope function. Return value for ‘<strong>let</strong>’, ‘<strong>run</strong>’, and ‘<strong>with</strong>’ functions is the lambda result.</p><pre>fun main() {<br>    var user = User(&quot;Joe&quot;,&quot;London&quot;)<br>    val updatedUsername = user.let {<br>        it.name = &quot;John&quot;<br>        it.name<br>    }<br>    println(&quot;Updated Username : $updatedUsername&quot;)<br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>Context object</h3><p>‘<strong>apply</strong>’ and ‘<strong>also’ </strong>functions return the context object itself. In this case, we don’t need to specify the return value. The context object is automatically returned.</p><pre>fun main() {<br>    var user = User(&quot;Joe&quot;,&quot;London&quot;)<br>    val updatedUser = user.apply {<br>        name = &quot;John&quot;    <br>    }<br>    println(&quot;Updated Username : ${updatedUser.name}&quot;)<br>}</pre><pre>data class User(var name: String, var address: String)</pre><p>Check the below table for the comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKcSbd2JwsQi9sACVoHmVw.png" /></figure><p>let’s see the kotlin scope functions in detail.</p><h3>Let</h3><p>Mostly used for null checks, when applying <strong><em>?.let </em></strong>on an object, we can rest safe that every time we access that object inside the scope function, the object will be <strong>not null</strong>. To reference the object inside the scope function, we use the keyword <strong><em>it</em></strong>.</p><blockquote><strong>Context Object — it</strong></blockquote><blockquote><strong>Returns — last statement</strong></blockquote><blockquote><strong>Use case</strong> — let function is often used to provide null safety calls. Use safe call operator(?.) with ‘let’ for null safety. It executes the block only with the non-null value.</blockquote><pre>fun main() {<br>    <br>    var user:User? = null<br>    user?.let {<br>        println(&quot;First Time : User $user&quot;)<br>    }<br>    user = User(&quot;John&quot;,&quot;India&quot;)<br>    user?.let {<br>        println(&quot;Second Time : User $user&quot;)<br>    }<br>}<br><br>data class User(var name: String, var address: String)</pre><h3>Run</h3><p>‘run’ function can be said as the combination of ‘<strong>let</strong>’ and ‘<strong>with</strong>’ functions.</p><blockquote><strong>Context Object</strong> — it</blockquote><blockquote><strong>Returns </strong>— last statement</blockquote><blockquote><strong>Use Case</strong> — Used when the object lambda contains both initialization and the computation of the return value. Using run we can perform null safety calls as well as other computations.</blockquote><p>It is the only scope function that has two variants.</p><h3>run as extension</h3><p>used to create a scope to run an operation over an object, and get a result.</p><pre>fun main() {<br>    val user = User(&quot;mani&quot;,&quot;India&quot;)<br>    val username = user?.run {<br>        name = generateFullName(name)<br>        name<br>    }<br>    println(username)<br>}</pre><pre>fun generateFullName(name: String) : String {<br>    return name + &quot; kandam&quot;<br>}</pre><pre>data class User(var name: String, var address: String)</pre><p><strong>Note: </strong>run returns the last statement of the function.</p><h3>run as function</h3><p>reduce the scope of certain variables, to avoid unnecessary access.</p><pre>fun main() {<br>    val user = User(&quot;mani&quot;,&quot;India&quot;)<br>    <br>    val username = run {<br>        generateFullName(user.name)<br>    }<br>    println(username)<br>}</pre><pre>fun generateFullName(name: String) : String {<br>    return name + &quot; kandam&quot;<br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>With</h3><p>Similar to <strong>apply </strong>function, with is also used to change properties of an instance i.e. object configuration. The only difference is <strong>with </strong>is not an extension function. The last expression of with function returns a result.</p><blockquote><strong>Context Object </strong>— this</blockquote><blockquote><strong>Returns </strong>— last statement</blockquote><blockquote><strong>Use Case</strong> — Run multiple operations on an object</blockquote><pre>fun main() {<br>    val user = User(&quot;mani&quot;,&quot;India&quot;)<br>    <br>    val username = with(user) {<br>    	name = &quot;Sathish&quot;<br>        address = &quot;USA&quot;<br>        name<br>    }<br>    <br>    println(username)<br>    <br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>Apply</h3><p>Basically, if you are initializing an object, and setting a bunch of properties like in this case, you have a pretty solid candidate to <strong><em>apply</em></strong><em> </em>this scope function.</p><blockquote><strong>Context Object — </strong>this</blockquote><blockquote><strong>Returns </strong>— same object</blockquote><blockquote><strong>Use Case — </strong>Initialize and configure an object</blockquote><pre>fun main() {<br>    val user = User(&quot;mani&quot;,&quot;India&quot;)<br>    <br>    val updatedUser = user.apply {<br>        name = &quot;Siva&quot;<br>        address = &quot;London&quot;<br>    }<br>    <br>    println(updatedUser)<br>    <br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>Also</h3><p>A common use also is for side effects without modifying the object. We can use it for doing some operations on the intermediate results. also does not transform the object. It returns the same object.</p><blockquote><strong>Context Object </strong>— it</blockquote><blockquote><strong>Returns </strong>— same object</blockquote><blockquote><strong>Use Case </strong>— It is used where we have to perform additional operations when we have initialized the object members.</blockquote><pre>fun main() {<br>    val user = User(&quot;mani&quot;,&quot;India&quot;)<br>    <br>    val updatedUser = user.apply {<br>        name = &quot;Siva&quot;<br>        address = &quot;London&quot;<br>    }.also {<br>        println(it)  <br>    }<br>   <br>}</pre><pre>data class User(var name: String, var address: String)</pre><h3>use-case</h3><ul><li>Many developers writing code in Kotlin but they follow Java’s coding style</li></ul><pre>val intent = Intent()<br>intent.putExtra(&quot;Key&quot;, &quot;value&quot;)<br>intent.putExtra(&quot;Key1&quot;, &quot;value&quot;)</pre><p><strong>How we can improve this code</strong> to make sure it’s concise and Kotlin friendly:</p><ul><li><strong>let</strong> : <em>returns the </em><strong><em>result</em></strong><em> of the</em><em>lambda</em></li></ul><pre>val intent = Intent().<em>let </em><strong>{<br>    it</strong>.putExtra(&quot;Key&quot;, &quot;value&quot;)<br>    <strong>it</strong>.putExtra(&quot;Key1&quot;, &quot;value&quot;)<br>    <strong>it</strong>.<em>action </em>= &quot;CUSTOM_APP_ACTION&quot; // <strong>Unit</strong><br><strong>}</strong>// here intent&#39;s type will be <strong>Unit 🥵</strong>// you can fix this by moving/removing last statement</pre><pre>val intent = Intent().<em>let </em><strong>{<br>    it</strong>.putExtra(&quot;Key&quot;, &quot;value&quot;)<br>    <strong>it</strong>.<em>action </em>= &quot;CUSTOM_APP_ACTION&quot;<br>    <strong>it</strong>.putExtra(&quot;Key1&quot;, &quot;value&quot;) // <strong>Intent ✅</strong><br><strong>}</strong></pre><ul><li><strong>apply</strong> : <em>returns its </em><em>receiver</em></li></ul><pre>val intent = Intent().<em>apply </em><strong>{<br>    </strong>putExtra(&quot;Key&quot;, &quot;value&quot;)<br>    putExtra(&quot;Key1&quot;, &quot;value&quot;)<br>    <em>action </em>= &quot;CUSTOM_APP_ACTION&quot;<br><strong>}</strong>// here intent&#39;s type will be <strong>Intent ✅</strong></pre><p>the summary of choosing between the scoped functions as a flowchart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsS3P98O0YLdLNSmeQTGXQ.png" /></figure><h3><strong>Conclusion</strong></h3><p>That’s all about the Scoped functions in Kotlin. I hope that this article has given you a clearer way of understanding and implementing the right scoped function in the right place.</p><p>Thank you so much for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3a5fabbeec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypted/Decrypted http request in android by Retrofit/OkHttp]]></title>
            <link>https://medium.com/@sumonedium/encrypted-decrypted-http-request-in-android-by-retrofit-okhttp-ca53f98185a1?source=rss-dec8e10d5f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca53f98185a1</guid>
            <category><![CDATA[decryption]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[interceptors]]></category>
            <dc:creator><![CDATA[SumOn Hasan]]></dc:creator>
            <pubDate>Wed, 17 Nov 2021 08:36:34 GMT</pubDate>
            <atom:updated>2021-11-24T11:07:30.586Z</atom:updated>
            <content:encoded><![CDATA[<p>In android development, Retrofit is a popular, simple and flexible library to handle network requests. Its adaptability to various use-cases is amazing because you can inject custom OkHttpClient Interceptors to intercept, change or modify requests and responses.</p><p>In this post I’m going to show with an example how we can adapt OkHttpClient interceptors to encrypt and decrypt requests and responses to and from a server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*t-FNY-1kndQOyAsU7OhHHg@2x.png" /></figure><h3><strong>Use Case</strong></h3><p>Let’s assume that as part of the security routine or standards in your organization, requests and responses to and from the server must be encrypted over the network. How then do you handle such using the Retrofit library?</p><p>Interceptors to the Rescue OkHttp library exposes an Interceptor interface which observes, modifies, and potentially short-circuits requests going out and the corresponding responses coming back in. Typically interceptors add, remove, or transform headers on the request or response.</p><p>In this example, we would create an Encryption and Decryption class that implements the Interceptor interface and override the intercept method. It is in the overridden method that we’ll handle our encryption and decryption before passing the class as part of the OkHttpClient builder.</p><p><strong>Let’s see this in code…</strong></p><p>We’ll use a utility class that handles the encryption and decryption and also use Postman mock server to mock our request and response.</p><p>As stated, our mock Api would only accept an encrypted string as request as well as return an encrypted string as a response to the client.</p><h3>Encryption Interceptor</h3><p>Lets add our Encryption interceptor that implements the Interceptor interface as follows:</p><pre>/**<br> *<br> * Retrofit Interceptor to intercept and encrypt response from the server<br> * <br> */</pre><pre>public class EncryptionInterceptor implements Interceptor {<br>    private static final String TAG = EncryptionInterceptor.class.getSimpleName();<br>    private final CryptoStrategy mEncryptionStrategy;</pre><pre>//injects the type of encryption to be used<br>    public EncryptionInterceptor(CryptoStrategy mEncryptionStrategy) {<br>        this.mEncryptionStrategy = mEncryptionStrategy;<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public Response intercept(Chain chain) throws IOException {<br>        Timber.i(&quot;===============ENCRYPTING REQUEST===============&quot;);<br>        Request request = chain.request();<br>        RequestBody rawBody = request.body();<br>        String encryptedBody = &quot;&quot;;</pre><pre>MediaType mediaType = MediaType.parse(&quot;text/plain; charset=utf-8&quot;);<br>        if (mEncryptionStrategy != null) {<br>            try {<br>                String rawBodyString = CryptoUtil.requestBodyToString(rawBody);<br>                encryptedBody = mEncryptionStrategy.encrypt(rawBodyStr);<br>                Timber.i(&quot;Raw body=&gt; %s&quot;, rawBodyStr);<br>                Timber.i(&quot;Encrypted BODY=&gt; %s&quot;, encryptedBody);<br>            } catch (Exception e) {<br>                e.printStackTrace();<br>            }<br>        } else {<br>            throw new IllegalArgumentException(&quot;No encryption strategy!&quot;);<br>        }<br>        RequestBody body = RequestBody.create(mediaType, encryptedBody);</pre><pre>//build new request<br>        request = request.<br>        newBuilder()<br>            .header(&quot;Content-Type&quot;, body.contentType().toString())<br>            .header(&quot;Content-Length&quot;, String.valueOf(body.contentLength()))<br>            .method(request.method(), body).build();</pre><pre>return chain.proceed(request);<br>    }</pre><pre>}</pre><h3>Decryption Interceptor</h3><p>Likewise, the response from the server needs to be decrypted and parsed to the necessary object. Let’s create a Decryption interceptor as follows:</p><pre>/**<br> * <br> * Retrofit Interceptor to intercept and decrypt response from the server<br> */<br>public class DecryptionInterceptor implements Interceptor {</pre><pre>private final CryptoStrategy mDecryptionStrategy;</pre><pre>//injects the type of decryption to be used<br>    public DecryptionInterceptor(CryptoStrategy mDecryptionStrategy) {<br>        this.mDecryptionStrategy = mDecryptionStrategy;<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public Response intercept(<a href="http://twitter.com/NonNull">@NonNull</a> Chain chain) throws IOException {<br>        Timber.i(&quot;===============DECRYPTING RESPONSE===============&quot;);<br>        <br>        Response response = chain.proceed(chain.request());<br>        if (response.isSuccessful()) {<br>            Response.Builder newResponse = response.newBuilder();<br>            String contentType = response.header(&quot;Content-Type&quot;);<br>            if (TextUtils.isEmpty(contentType)) contentType = &quot;application/json&quot;;<br>            String responseString = response.body().string();</pre><pre>String decryptedString = null;<br>            if (mDecryptionStrategy != null) {<br>                try {<br>                    decryptedString = mDecryptionStrategy.decrypt(responseStr);<br>                } catch (Exception e) {<br>                    e.printStackTrace();<br>                }</pre><pre>Timber.i(&quot;Response string =&gt; %s&quot;, responseStr);<br>                Timber.i(&quot;Decrypted BODY=&gt; %s&quot;, decryptedString);<br>            } else {<br>                throw new IllegalArgumentException(&quot;No decryption strategy!&quot;);<br>            }<br>            newResponse.body(ResponseBody.create(MediaType.parse(contentType), decryptedString));<br>            return newResponse.build();<br>        }<br>        return response;<br>    }<br>}</pre><h3>Retrofit Api Service</h3><p>The Retrofit <strong>saveUser </strong>service saves a Book object to the server. But the Encryption class is meant to intercept and convert the <strong>User </strong>object to an encrypted string.</p><pre>public interface ApiService {<br><a href="http://twitter.com/POST">@POST</a>(&quot;save-user&quot;)<br> Call&lt;Book&gt; saveUser(<a href="http://twitter.com/Body">@Body</a> User user);<br>}</pre><h3>OkHttp and Retrofit Client</h3><p>With the interceptors created, we need to create OkHttpClient and add encryption and decryption interceptors. We need to be <strong>aware of the order</strong> in which we add interceptors. Ideally, the server first receives a request that then responds with a response. So we need to add encryption interceptor before decryption interceptor because it works on response data.</p><p>Once the interceptors have been added to OkHttpClient, we can now add OkHttpClient to the Retrofit Builder as shown below.</p><pre>public class App extends Application {<br>    private static final String TAG = App.class.getSimpleName();<br>    private static final String BASE_URL = &quot;<a href="https://66d252d7-61d1-44e0-be70-1f77477ac86c.mock.pstmn.io/">https://66d252d7-61d1-44e0-be70-1f77477ac86c.mock.pstmn.io</a>&quot;;</pre><pre>private static App INSTANCE;</pre><pre>private ApiService apiService;</pre><pre>public static App get() {<br>        return INSTANCE;<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void onCreate() {<br>        super.onCreate();<br>        INSTANCE = this;</pre><pre>OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();</pre><pre>        // Gson Builder<br>        GsonBuilder gsonBuilder = new GsonBuilder();<br>        Gson gson = gsonBuilder.create();</pre><pre>        // HttpLoggingInterceptor<br>        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(message -&gt; Timber.i(message));<br>        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);</pre><pre>        /**<br>         * injection of interceptors to handle encryption and   decryption<br>         */</pre><pre>        // Encryption Interceptor<br>        EncryptionInterceptor encryptionInterceptor = new EncryptionInterceptor(new EncryptionImpl());<br>        //Decryption Interceptor<br>        DecryptionInterceptor decryptionInterceptor = new DecryptionInterceptor(new DecryptionImpl());</pre><pre>        // OkHttpClient. Be conscious with the order<br>        OkHttpClient okHttpClient = new OkHttpClient()<br>                .newBuilder()<br>                //httpLogging interceptor for logging network requests<br>                .addInterceptor(httpLoggingInterceptor)<br>                //Encryption interceptor for encryption of request data<br>                .addInterceptor(encryptionInterceptor)<br>                // interceptor for decryption of request data<br>                .addInterceptor(decryptionInterceptor)<br>                .build();</pre><pre>        //Retrofit<br>        Retrofit retrofit = new Retrofit.Builder()<br>                .client(okHttpClient)<br>                .baseUrl(BASE_URL)<br>                // for serialization<br>             .addConverterFactory(GsonConverterFactory.create(gson))<br>                .build();</pre><pre>        //ApiService<br>        apiService = retrofit.create(ApiService.class);</pre><pre>}</pre><pre>public ApiService getApiService() {<br>        return apiService;<br>    }</pre><pre>}</pre><p>With the client in place, we can call the <strong>saveUser</strong> service in the MainActivity.java file as follows:</p><pre>public class MainActivity extends AppCompatActivity {</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_main);</pre><pre>Button saveButton = findViewById(R.id.saveBook);</pre><pre>ApiService apiService= App.get().getApiService();<br>        User user = new Book(&quot;the lost symbol&quot;, &quot;Dan Brown&quot;, &quot;September 15, 2009&quot;);</pre><pre>saveButton.setOnClickListener(view -&gt;<br>                apiService.saveUser(user).<br>                        enqueue(new Callback&lt;Book&gt;() {<br>                            <a href="http://twitter.com/Override">@Override</a><br>                            public void onResponse(Call&lt;User&gt; call, Response&lt;Book&gt; response) {<br>                                if (response.isSuccessful()) {<br>                                    log.d(&quot;Response from Server:&quot;, response.body().toString());<br>                                }<br>                            }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>                            public void onFailure(Call&lt;User&gt; call, Throwable t) {<br>                                //do something</pre><pre>}<br>                        }));</pre><pre>}<br>}</pre><p>When you run the app, you’d find the encrypted &amp; decrypted user object in the log.</p><h3>Conclusion</h3><p>In the case of explained above, it can be seen that OkHttp Interceptors offer a great tool for handling requests and responses as well as converting the content of request headers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca53f98185a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Workmanager : Onetime and Periodic work request — Android]]></title>
            <link>https://medium.com/@sumonedium/android-jetpack-workmanager-onetime-and-periodic-work-request-94ace224ff7d?source=rss-dec8e10d5f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/94ace224ff7d</guid>
            <category><![CDATA[periodic-work]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[workmanager]]></category>
            <category><![CDATA[one-time-work]]></category>
            <dc:creator><![CDATA[SumOn Hasan]]></dc:creator>
            <pubDate>Sun, 19 Sep 2021 18:48:12 GMT</pubDate>
            <atom:updated>2021-09-19T18:59:31.106Z</atom:updated>
            <content:encoded><![CDATA[<p>Work Manager is an API introduced and developed by Google that allows you to perform asynchronous, periodic and scheduled tasks on Android in a much more efficient way than conventional methods.</p><p>Android developers know the hassle of identifying a user’s device and then choose to assign a task between JobScheduler, Firebase JobDispatcher, ScheduledExecutorService, or AlarmManager.</p><p>WorkManager gets rid of this pain point. Selecting one of the following three APIs will automatically lift all the weights for you as you want them to work:</p><ol><li>JobScheduler</li><li>Firebase JobDispatcher</li><li>Alarm Manager</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeyRYZFErHogkJPVHgw-eQ.png" /></figure><p>To give you an idea, Work Manager is perfect for the apps you need:</p><ul><li>Return data periodically. Example: Weather app</li><li>Perform an action at a specific time. Example: Reminder based apps</li><li>Periodically upload data to a server.</li><li>Perform a task based on device information. Example: Battery status<br>… and more!</li></ul><h3>Exploring WorkManager’s components</h3><p>The WorkManager API has 3 main components:</p><ol><li>Worker</li><li>WorkRequest</li><li>WorkManager</li></ol><p>Let’s explore these components further.</p><h3>Worker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*KspjEk3nA9Kv_pq7R8Gfow.jpeg" /></figure><p>It is a component of the WorkManager API that actually performs the task. It is responsible for determining what needs to be done. You will need to override the doWork() method and your long-term code will move inside this method.</p><p>The doWork() method performs the task in the background thread. The doWork() method returns a result, which is an enum with the following values:</p><ul><li>Result.success() — The task has been performed successfully</li><li>Result.failure() — Task failed permanently; It will not be tried again</li><li>Result.retry()<strong> </strong>— The work failed but needs to be retried according to the specified backoff policy.</li></ul><h3>WorkRequest</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*DeXlCHTGngTq4BCR-Iljog.jpeg" /></figure><p>A WorkRequest is responsible for specifying which Worker should run. It takes in a Worker and performs the task specified in the Worker.</p><p>There are two types of WorkRequests:</p><ul><li>OneTimeWorkRequest – For one-time tasks, i.e. non-repeating tasks.</li><li>PeriodicWorkRequest – For repeating tasks.</li></ul><p>Both these requests are built with one of the subclasses of WorkRequest.Builder, which is either OneTimeRequestBuilder or PeriodicRequestBuilder.</p><p>When a WorkRequest is created, an ID associated with the request is also created, which is a of type UUID. You can also set a tag for your WorkRequest if you want to access it later via the tag, and a <a href="https://developer.android.com/reference/androidx/work/BackoffPolicy"><em>backoff policy</em></a> in case you want to reschedule the work.</p><p>There are two more significant things that you might want to use in your WorkRequest:</p><h4>Constraints</h4><p>The Constraints.Builder helper class lets you specify certain criteria which makes sure that your Worker only runs if these criteria are met. Some of these criteria include:</p><ul><li>setRequiresCharging(boolean requiresCharging) – set to true if you want to run your Worker only when the device is charging.</li><li>setRequiresDeviceIdle(boolean requiresDeviceIdle) – set to true if you want to run your Worker only when the device is idle.</li><li>setRequiresBatteryNotLow(boolean requiresBatteryNotLow) – set to true if you don’t want to run your Worker when the device’s battery is low.</li><li>setRequiresStorageNotLow(boolean requiresStorageNotLow) – set to true if you don’t want to run your Worker when the device’s storage is low.</li><li>setRequiredNetworkType(NetworkType networkType) – sets the <a href="https://developer.android.com/reference/androidx/work/NetworkType">NetworkType</a> with which the Worker should run.</li><li>addContentUriTrigger(Uri uri, boolean triggerForDescendants) – runs the Worker when a content Uri is updated. If triggerForDescendants is true, the criteria is matched for its descendants too.</li></ul><h4>Data</h4><p>The Data.Builder helper class lets you provide data to your Worker.</p><p>Please keep in mind that this should not exceed 10KB.You will get an IllegalStateException if you pass data that exceeds this limit.</p><p>Think of Data as a key-value pairs store, not unlike SharedPreferences. You can find out more about it <a href="https://developer.android.com/reference/androidx/work/Data.Builder">here</a>.</p><h3>Adding WorkManager to your project</h3><p>Adding the WorkManager API to your app is simple. You just need to add the following dependencies to your app-level build.gradle file and you’re all set:</p><pre>dependencies {<br>    implementation(<strong>&quot;androidx.work:work-runtime-ktx:2.5.0&quot;</strong>)<br>}</pre><h3>Creating a Worker</h3><p>For the sake of this tutorial, we shall assume that the long running task we need to run via our WorkManager API is backing up data to the cloud. This is done via our backupData() method.</p><p>We’re gonna name our Worker as BackupWorker, and run our backupData() method inside the doWork() method after overriding it.</p><pre>class BackupWorker(context : Context, params : WorkerParameters) : Worker(context, params) {</pre><pre>    override fun doWork(): Result {</pre><pre>        // Perform your long-running backup operation here.<br>        backupData()</pre><pre>        // Return SUCCESS if the task was successful.<br>        // Return FAILURE if the task failed and you don’t want to retry it.<br>        // Return RETRY if the task failed and you want to retry it.<br>        return Result.SUCCESS<br>    }<br>}</pre><h3>One-time work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwXcp-PmqVL7CNWfIubG1A.png" /></figure><p>You can read more about how to build PeriodicWorkRequest <a href="https://developer.android.com/reference/androidx/work/OneTimeWorkRequest.Builder">here</a>.</p><h4>Build:</h4><p>Let’s build a OneTimeRequest with the OneTimeRequestBuilder and pass our BackupWorker to it as followed:</p><pre>val backupWorkRequest = OneTimeWorkRequestBuilder&lt;BackupWorker&gt;().build()</pre><p>That’s how easy it is to build a OneTimeRequest with WorkManager! Now let’s add some Constraints, Data that has the user’s name, and a tag. It’s ideal if we let the device backup data only when it’s charging and if storage isn’t low. So let’s see how to do this and create some constraints:</p><pre>val constraints = Constraints.Builder()<br>            .setRequiresCharging(true)<br>            .setRequiresStorageNotLow(true)<br>            .build()</pre><pre>val data = Data.Builder()<br>        .putString(“DATA_USER_FIRSTNAME”, “John”)	<br>        .build()</pre><pre>val backupWorkRequest = OneTimeWorkRequestBuilder&lt;BackupWorker&gt;()<br>                    .setConstraints(constraints)<br>                    .setInputData(data)<br>                    .addTag(“BACKUP_TAG”)<br>                    .build()</pre><h4>Run:</h4><p>Executing your WorkRequest with WorkManager is easy. You just need to get an instance of WorkManager and enqueue the request. Here’s how that can be done:</p><pre>val backupWorkRequest = OneTimeWorkRequestBuilder&lt;BackupWorker&gt;()<br>                    .setConstraints(constraints)<br>                    .build()</pre><pre>WorkManager.getInstance().enqueue(backupWorkRequest)</pre><h4>Observing the state</h4><p>Like we mentioned above, the WorkManager API lets you observe the <a href="https://developer.android.com/reference/androidx/work/State">State</a> of your WorkRequest. There are enum values in the State class:</p><ul><li>BLOCKED – Request is awaiting to be executed.</li><li>ENQUEUED – Request is enqueued for execution.</li><li>RUNNING – Request is currently being executed.</li><li>SUCCEEDED – Request completed successfully.</li><li>CANCELLED – Request has been cancelled.</li><li>FAILED – Request has failed.</li></ul><p>We can get the ID of a WorkRequest with the getStatusById() method and call the observe() method to observe the state of the request. Let’s see how to do this:</p><pre>WorkManager.getInstance()<br>    .getStatusById(backupWorkRequest.id)<br>    .observe(lifecycleOwner, Observer { workStatus -&gt;<br>        if (workStatus != null &amp;&amp; workStatus.state.isFinished) {<br>            // Do something here if request has finished executing.<br>        }<br>    })</pre><h4>Cancel:</h4><p>You can cancel a WorkRequest by calling the cancelWorkById() method or even the cancelAllWorkByTag() method if you want to cancel it by passing the tag of the WorkRequest.</p><pre>WorkManager.getInstance().cancelWorkById(backupWorkRequest.getId())</pre><blockquote>It’s noteworthy to mention that your WorkRequest may not be canceled by the WorkManager if it is already running or has finished.</blockquote><h3>Periodic work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRzoNR10YZPSGExbPK5ulQ.png" /></figure><h4>Build:</h4><p>you can also set up recurring tasks with the PeriodicWorkRequest class. The following code snippet sets up a PeriodicWorkRequest to run every 24 hours:</p><pre>val periodicWorkRequest = PeriodicWorkRequestBuilder&lt;BackupWorker&gt;(24, TimeUnit.HOURS).build()</pre><p>You can read more about how to build PeriodicWorkRequest <a href="https://developer.android.com/reference/androidx/work/PeriodicWorkRequest.Builder">here</a>.</p><h4>Run:</h4><pre>WorkManager.getInstance().enqueueUniquePeriodicWork(<br>    <strong>&quot;</strong>uniqueWorkName<strong>&quot;</strong>,<br>    ExistingPeriodicWorkPolicy.<em>KEEP</em>,<br>    periodicWorkRequest<br>)</pre><p>There are more advanced usages of the WorkManager, but they aren’t covered in this article. You can fine-tune WorkManager and leverage advanced features provided by the API, like:</p><ul><li>Unique sequence of tasks, to run only one instance of a specific set of tasks;</li><li>Chained sequence of tasks, to run tasks in a specified order;</li><li>Tasks that take input data and return output data.</li></ul><p>You can learn more on how to do this in the official documentation <a href="https://developer.android.com/topic/libraries/architecture/workmanager/advanced">here</a>.</p><h3>Conclusion</h3><p>It is a great choice to schedule and perform tasks in the background in your Android app. It could be the ideal API to use because of its ease-of-use and regular API updates, thanks to Google making it a part of the Android Architecture Components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94ace224ff7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OkHttp: How to Refresh Access Token Efficiently]]></title>
            <link>https://medium.com/@sumonedium/okhttp-how-to-refresh-access-token-efficiently-6dece4d271c0?source=rss-dec8e10d5f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dece4d271c0</guid>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[SumOn Hasan]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 14:58:35 GMT</pubDate>
            <atom:updated>2021-08-26T15:13:27.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykCMBEFMbaT0QrzsgxkiCw.jpeg" /></figure><p>In token-based authentication, including OAuth, there are two tokens: an <strong>access token</strong> and a <strong>refresh token</strong>. Whenever you want to access a protected asset, you must use an access token to grant access. A refresh token is a special kind of token. This can be used to get a renewed access token because an access token has a shorter life cycle. The value of expires_in in the response shows how long the access token is valid.</p><pre>{<br>  &quot;token_type&quot;:&quot;bearer&quot;,<br>  &quot;access_token&quot;:&quot;{ACCESS_TOKEN_VALUE}&quot;,<br>  &quot;expires_in&quot;:3600,<br>  &quot;refresh_token&quot;:&quot;{REFRESH_TOKEN_VALUE}&quot;<br>}</pre><p>Typically, an access token is used in the request header. OkHttp supports a handy way to tweak your request before sending it, which is Interceptor. With that, you can add an access token information in the header easily without modifying your request call methods.</p><pre>OkHttpClient client = okHttpClient.newBuilder()<br>  .addInterceptor(new AccessTokenInterceptor())<br>  .build();</pre><pre>public class AccessTokenInterceptor implements Interceptor {<br><br>  private final AccessTokenRepository accessTokenRepository;<br><br>  public AccessTokenInterceptor(AccessTokenRepository accessTokenRepository) {<br>    this.accessTokenRepository = accessTokenRepository;<br>  }<br><br>  @Override<br>  public Response intercept(Chain chain) throws IOException {<br>    String accessToken = accountRepository.getAccessToken();<br>    Request request = newRequestWithAccessToken(chain.request(), accessToken);<br>    return chain.proceed(request);<br>  }<br><br>  @NonNull<br>  private Request newRequestWithAccessToken(@NonNull Request request, @NonNull String accessToken) {<br>    return request.newBuilder()<br>            .header(&quot;Authorization&quot;, &quot;Bearer &quot; + accessToken)<br>            .build();<br>  }<br>}</pre><p>This works while an access token is valid. Since the access token can be expired, you need to think how to refresh it. One simple approach is to set a schedule job to refresh before expires_in. It could work but there are things you need to consider.</p><ul><li><strong>Application Lifecycle</strong>: When an application is stopped, a scheduled job could be gone. You would reschedule the job with considering the last refresh time when the application is started.</li><li><strong>Unnecessary Refresh</strong>: When a user doesn’t access a protected resource for a long time, you don’t need to refresh an access token. If there is a refreshing every 60 minute considering expires_in, there would be unnecessary refreshing 24 times for one day.</li></ul><h3>Interceptor Approach</h3><p>Interceptor allows you not only to modify your request but also to send a request and get a response. When an access token is expired, there is an HTTP unauthorized error, with 401 error code, from the backend. That is the best time to refresh an access token.</p><p>Below code shows how to do it. First, you need to send a refresh access token request. Then, retry the original request with the renewed access token. There are multiple threads in OkHttp to handle requests. It is important to use synchronized to avoid additional refreshing.</p><pre>public class AccessTokenInterceptor implements Interceptor {<br><br>  ...<br><br>  @Override<br>  public Response intercept(Chain chain) throws IOException {<br>    String accessToken = accessTokenRepository.getAccessToken();<br>    Request request = newRequestWithAccessToken(chain.request(), accessToken);<br>    Response response = chain.proceed(request);<br><br>    if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {<br>      synchronized (this) {<br>        final String newAccessToken = accessTokenRepository.getAccessToken();<br>        // Access token is refreshed in another thread.<br>        if (!accessToken.equals(newAccessToken)) {<br>            return chain.proceed(newRequestWithAccessToken(request, newAccessToken));<br>        }<br><br>        // Need to refresh an access token<br>        final String updatedAccessToken = accessTokenRepository.refreshAccessToken();<br>        // Retry the request<br>        return chain.proceed(newRequestWithAccessToken(request, updatedAccessToken));<br>      }<br>    }<br><br>    return response;<br>  }<br><br>  ...<br>}</pre><h3>Authenticator Approach</h3><p>The interceptor method may be good enough to refresh an access token. Since token-based authentication is becoming commonplace, OkHttp is a good way to support authentication. Authenticator is specifically designed to refresh an access token. There are three main benefits to using:</p><ul><li><strong>Auto Retry</strong>: If you set a request, it will retry it up to 20 times by default.</li><li><strong>No Response Code Check</strong>: In the interceptor method, you check the response code manually to determine refreshing. Authentication is called whenever there is an HTTP unauthorized error, so you do not need to verify.</li><li><strong>No Interceptor Side Effect</strong>: OkHttp can have multiple Interceptors. Each interceptor is called orderly what you set and next Interceptor is executed when chain.proceed() is called. In Interceptor approach, there are two chain.proceed(). One is for the original request and the other is for retry request. In each time, the next Interceptor is executed, so AnotherInterceptor could be called twice. Depending on what it does, this could make a side effect.</li></ul><p>Authenticator is triggered for every HTTP unauthorized error. For some authentication type such as Basic, it is not needed to refresh the access token. So, below code checks the header information first. The return type is @Nullable. If you return null, it doesn’t do anything. Also, unlike Interceptor, it returns Request not Response.</p><pre>OkHttpClient client = okHttpClient.newBuilder()<br>  .authenticator(new AccessTokenAuthenticator())<br>  .addInterceptor(new AccessTokenInterceptor())<br>  .build();</pre><pre>public class AccessTokenAuthenticator implements Authenticator {<br><br>  private final AccessTokenRepository accessTokenRepository;<br><br>  public AccessTokenAuthenticator(AccessTokenRepository accessTokenRepository) {<br>    this.accessTokenRepository = accessTokenRepository;<br>  }<br><br>  @Nullable<br>  @Override<br>  public Request authenticate(Route route, Response response) {<br>    final String accessToken = accountRepository.getAccessToken();<br>    if (!isRequestWithAccessToken(response) || accessToken == null) {<br>        return null;<br>    }<br>    synchronized (this) {<br>        final String newAccessToken = accountRepository.getAccessToken();<br>        // Access token is refreshed in another thread.<br>        if (!accessToken.equals(newAccessToken)) {<br>            return newRequestWithAccessToken(response.request(), newAccessToken);<br>        }<br><br>        // Need to refresh an access token<br>        final String updatedAccessToken = accountRepository.refreshAccessToken();<br>        return newRequestWithAccessToken(response.request(), updatedAccessToken);<br>    }<br>  }<br><br>  private boolean isRequestWithAccessToken(@NonNull Response response) {<br>      String header = response.request().header(&quot;Authorization&quot;);<br>      return header != null &amp;&amp; header.startsWith(&quot;Bearer&quot;);<br>  }<br><br>  @NonNull<br>  private Request newRequestWithAccessToken(@NonNull Request request, @NonNull String accessToken) {<br>      return request.newBuilder()<br>              .header(&quot;Authorization&quot;, &quot;Bearer &quot; + accessToken)<br>              .build();<br>  }<br>}</pre><h3>Conclusion</h3><p>OkHttp well supports token-based authentication. <strong>Interceptor </strong>lets you easily add access token information to the header. To refresh the access token, you can use authentication. It is specifically designed for this and is triggered only if there is an HTTP unauthorized error. Moreover, it will retry automatically and will not call the <strong>interceptor </strong>extra.</p><p>Ref: <a href="https://www.youtube.com/watch?v=tPIdWALEVLc">https://www.youtube.com/watch?v=tPIdWALEVLc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dece4d271c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live internet check on android via EagleEye]]></title>
            <link>https://medium.com/@sumonedium/live-internet-check-on-android-via-eagleeye-99472c794316?source=rss-dec8e10d5f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/99472c794316</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[liveinternet]]></category>
            <dc:creator><![CDATA[SumOn Hasan]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 11:45:16 GMT</pubDate>
            <atom:updated>2020-07-09T11:45:16.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>Detect internet status in real time on android via EagleEye.</h3><p>When your app has strict dependency to internet connectivity, it is good way to detect if the internet connection available or not when the app starts. Some developers might even implement observer for internet connection states so that the app can detect if the status changes at the middle of the operations and take proper actions i.e. let user know about connection status change, revert/resume ongoing pending operations etc.</p><p>So how can we check if the internet is available and connected in the device?</p><p>I developed <a href="https://github.com/SumonHub/EagleEye">EagleEye</a> to help other. It can give you on time network status any where in the app and very easy to use.</p><h3>Gradle Dependency</h3><p>Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:</p><pre>allprojects {<br>      repositories {<br>        ...<br>        maven { url &#39;https://jitpack.io&#39; }<br>      }<br>    }</pre><p>Step 2. Add the dependency</p><pre>dependencies {<br>            implementation &#39;com.github.SumonHub:EagleEye:1.0.0&#39;<br>    }</pre><h3>To-do</h3><h3>Enable EagleEye</h3><p>If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;     package=&quot;com.example.myapp&quot;&gt;<br>&lt;application             android:name=&quot;org.sumon.eagleeye.EagleEyeApplication&quot; &gt;         <br>...     <br>&lt;/application&gt; <br>&lt;/manifest&gt;</pre><p>If you do override the Application class, change it to extend EagleEyeApplication (if possible) as follows:</p><p>public class MyApplication extends EagleEyeApplication { ... }</p><h3>Use</h3><p>In your activity/fragment get status like below</p><pre>EagleEyeObserver.setConnectivityListener(new OnChangeConnectivityListener() {     <br>@Override     <br>public void onChanged(boolean status) {  <br>      Toast.makeText(MainActivity.this, &quot;&quot; + status,        Toast.LENGTH_SHORT).show();<br>  } <br>}); </pre><h3>Preview</h3><p><a href="https://github.com/SumonHub/EagleEye/blob/master/preview/demo.gif">https://github.com/SumonHub/EagleEye/blob/master/preview/demo.gif</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99472c794316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn your website into an android app]]></title>
            <link>https://medium.com/@sumonedium/turn-your-website-into-an-android-app-a91f30d7fff5?source=rss-dec8e10d5f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91f30d7fff5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[sumonhub]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[SumOn Hasan]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 11:13:02 GMT</pubDate>
            <atom:updated>2020-07-09T11:13:02.357Z</atom:updated>
            <content:encoded><![CDATA[<p>Android’s <a href="https://developer.android.com/guide/webapps/webview.html">WebView</a> allows you to integrate a webpage as a part of the app. WebView comes with all the features that of a desktop browser like managing history, cookies, HTML5 support and lot more. Using webview you can build very cool apps like integrating HTML5 games in the app.</p><h3>Gradle Dependency</h3><p>Open app label <strong>build.gradle</strong> and add <a href="https://github.com/SumonHub/WebviewClassic">this</a> library support. This lib build to use android webview to most efficient way.</p><p>build.gradle</p><pre>allprojects {<br>      repositories {<br>        ...<br>        maven { url &#39;https://jitpack.io&#39; }<br>      }<br>    }</pre><pre>dependencies {<br>           implementation &#39;com.github.SumonHub:WebViewClassic:1.0.2&#39;<br>    } <br></pre><h3>How to use</h3><p>Step 1. create an empty activity in android studio (File&gt;New&gt;Acivity&gt;Empty Ativity)</p><p>Step 2. in xml file paste bellow code</p><pre>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>      android:layout_width=&quot;fill_parent&quot;<br>      android:layout_height=&quot;fill_parent&quot;<br>      android:orientation=&quot;vertical&quot; &gt;<br><br>      &lt;WebView<br>          android:id=&quot;@+id/webView1&quot;<br>          android:layout_width=&quot;fill_parent&quot;<br>          android:layout_height=&quot;fill_parent&quot; /&gt;<br>  &lt;/LinearLayout&gt; <br></pre><p>Step 3. In onCreate() method in .java file paste bellow code</p><pre>webView = findViewById(R.id.webView1);<br>webUrl = &quot;YOUR_WEB_URL&quot;;<br>WebViewClassic webViewClassic = new WebViewClassic(this,webView,webUrl);<br>webViewClassic.startWebView();</pre><p>Step 4. if you want back capability override onBackPressed() like bellow</p><pre>@Override<br>      // Detect when the back button is pressed<br>      public void onBackPressed() {<br>          if (webView.canGoBack()) {<br>              webView.goBack();<br>          } else {<br>              // Let the system handle the back button<br>              super.onBackPressed();<br>          }<br>      } </pre><p>run the app and enjoy!!! some useful method given below :)</p><h3>Public method</h3><pre>webViewClassic.setCustomDialog(progressDialog); // default progressDialog<br>webViewClassic.setDialogDuration(10*1000); // default 2000<br>webViewClassic.setClearCache(true); // default false</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91f30d7fff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>