2

By calling Thread.sleep on the UI thread i expect my android app to crash, but it does not.

I tried to explicitly run this on UI thread, by using runOnUiThread but the result was the same, the app freezes but not crashing.

Should i expect the app to crash when using Thread.sleep(6000) on the UI thread?

public class CrashActivity extends Activity {

@Override
protected void onResume() {
    super.onResume();

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(50000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

I am trying to simulate ANR!

3 Answers3

2

Thread.sleep(miliseconds) "causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds"

means,

If you are calling Thread.sleep() on MainThread i.e UI thread, It will freeze the UI and causes the thread to definitely stop executing for a given amount of time; So if there is no other thread needs to be run, CPU will goes in Idle mode. I think It won't create ANR.

ANR situation will happen if some large operation is going to operate on UI thread. Consider this example of calculation..

If you are clicking on Button and perform a code like -

public void onClick(View v) {
    ....
    int a = 1;
    while(true) {
       a++;
    }
}

This will cause an ANR.
Here is some reference about ANR -

Check out this documentation How to avoid ANR

Community
  • 1
  • 1
Paresh P.
  • 6,677
  • 1
  • 14
  • 26
0

As already explained Thread.sleep() won't crash your application by itself. It only parks your thread to a sleep mode for a number of milliseconds that you passed as an argument.

Scenario 1:

You are executing your Thread.sleep in the main Thread. The UI response gets stopped or it freezes. That means any interaction with the application by the user won't be possible.

If your timeout is so high, let's say 30 mins and you keep trying to interact with the application, the operating system will give you a chance to forcefully exit your program.

Scenario 2:

You are executing your Thread.sleep() in a different Thread or doing Asynchronously. Your application will respond to all your interactions. It also doesn't crash your application.

For background tasks you can use

Stenal P Jolly
  • 737
  • 9
  • 20
  • ANR (A pplication N to R esponding )is due to handling the long-running task in Main Thread(UI thread).If the main thread is stopped for more than 5 sec you get ANR. – Stenal P Jolly Mar 28 '17 at 05:26
0

If you want to stimulate ANR, then do not call Thread.sleep(). It will not work. Just start any function which takes long time to execute. Like loading a huge image file on main activity, etc.

Sonam
  • 572
  • 4
  • 13