kotlinapp-inventor

How to convert this AppInventor Blocks to Kotlin Code? Any Idea


Hi there I want to convert those blocks from the AppInventor project to Android Studio Project Using Kotiln as my programing language but I am very new to android development can anyone help me with that?

enter image description here

What this app does is opening webview and reload my webpage URL at a randomly generated time.

What I tried so far!

package com.technosoftkpk.y_view

import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myWebView: WebView = findViewById(R.id.webview)
        myWebView.setWebViewClient(WebViewClient())
        myWebView.loadUrl("https://technosoft.pk")
        val webSettings = myWebView.settings
        webSettings.displayZoomControls = true
        webSettings.javaScriptEnabled = true

        
    }
}

Solution

  • Would something like this work? This will randomly wait between 0 and 5 seconds. (Add the code at the end of onCreate):

    import kotlin.concurrent.thread
    import kotlin.random.Random
    
    thread {
        while (true) {
            Thread.sleep(Random.nextLong(5000))
            runOnUiThread { myWebView.reload() }
        }
    }
    

    This might look complicated, but we need to make a new thread to avoid blocking the UI thread and allowing user input. But then the reloading needs to happen on the UI thread again. An alternative would be to use postDelayed.