Hi , I want to force ANR trigger in my app. Base o...
# android
j
Hi , I want to force ANR trigger in my app. Base on ANR trigger concept https://developer.android.com/topic/performance/vitals/anr I use below code to reproduce
Copy code
viewModelScope.launch(Dispatchers.Main) {
            while (true) {}
        }
OR
Copy code
viewModelScope.launch(Dispatchers.Main) {
   delay(TimeUnit.SECONDS.toMillis(5))
}
But UI is stuck but ANR does not occur … Any help?
k
Hi, you can reproduce ANR with coroutine like below:
Copy code
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<TextView>(R.id.text_button).setOnClickListener {
            GlobalScope.launch(Dispatchers.Main) {
                while (true) {

                }
            }
        }
    }
When nothing else happens on the main thread, you will not see an ANR pop up immediately. You can trigger it by pressing the button and wait a few seconds.
j
@Kohei Moroi Thank for reply. Actually, I have tried above code but the dialog still does not show . Basically, I have a simple screen with 2 button. Button A calls
forceANR()
function, Button B is a normal button just log something such as “click button B”. So, when I click on button A, the screen is stuck. It is blocked that I can not click on button B. What’s problem here ?
Copy code
fun forceANRError() {
    GlobalScope.launch(Dispatchers.Main) {
        while (true) {
        }
    }
}

fun onClickButtonA() { forceANRError() }
fun onClickButtonB() { Log.d("Click Button B") }
Ah, I solved my problem !
👍 2
a
@Jason I have inspired more in your replayed than answered above. Thanks for your inspiring thoughts.
👍 1