Yes you are right , according to the documentation -
Android applications normally run entirely on a single thread by default the "UI thread" (or "main thread"). This means anything your application is doing in the UI thread that takes a long time to complete.
Therefore, any method that runs in the UI thread should do as little
work as possible on that thread. In particular, activities should do
as little as possible to set up in key life-cycle methods such as
onCreate() and onResume(). Potentially long running operations such as
network or database operations, or computationally expensive
calculations such as resizing bitmaps should be done in a worker
thread (or in the case of databases operations, via an asynchronous
request).
Though you can call wordCall
method by giving StrictMode ThreadPolicy
permission , but use it for debugging purpose only .
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_account)
val policy = ThreadPolicy.Builder()
.permitAll().build()
StrictMode.setThreadPolicy(policy)
//call method now
}
I think im on the right track and I believe the error is I need to use runOnUiThread but im not sure how to implement it.
Based on your thinking I am sharing example code , you may check - we will use schedule
method of timer to schedule a task , and retrieve the response body and set text of result to a textview through runOnUiThread
.
Here it is -
package com.example.kotlin
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import okhttp3.OkHttpClient
import okhttp3.Request
import java.lang.Exception
import java.net.URL
import java.util.*
import android.app.Activity
import android.content.Context
class CreateAccount : AppCompatActivity() {
lateinit var textView: TextView
var timer = Timer()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_account)
timer.schedule(WordCall(this), 0, (30 * 60 * 1000).toLong())
}
}
class WordCall(val context: Context) : TimerTask() {
override fun run() {
val textView: TextView = (context as Activity).findViewById(R.id.blue)
val client = OkHttpClient()
val url = URL("https://reqres.in/api/users?page=2")
val request = Request.Builder()
.url(url)
.get()
.build()
try {
val response = client.newCall(request).execute()
val responseBody = response.body()!!.string()
(context as Activity).runOnUiThread {
textView.text = "Response Body: $responseBody"
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}