0

I am using a worker thread, as described here but still the code is blocking the UI. If I sleep at the beginning of the run() method, it doesn't block the UI. The thing is, it's a heavy code that runs from the onCreate method, but no matter what I do, I can't make it not block the UI. What am I doing wrong?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                Log.d("asdf", "asdf");
            }
        }
    }).start();
}
Kalisky
  • 1,141
  • 1
  • 9
  • 18
  • 3
    Can we see some of the code you're expressing has a problem? – Justin Jasmann Jan 21 '13 at 22:15
  • 2
    what makes you think that it is blocking the UI thread as is? – FoamyGuy Jan 21 '13 at 22:20
  • @A--C, have you ever seen a thread in android? [here](http://android-developers.blogspot.de/2009/05/painless-threading.html) – vault Jan 21 '13 at 22:26
  • hey, you're right... it's something else! back to the drawing board... thanks for your time – Kalisky Jan 21 '13 at 22:28
  • @vault You're right, I have never seen a Thread in Android. Ty for the link! – A--C Jan 21 '13 at 22:29
  • Thread is taking a new Runnable because that is one of the ways you create an anonymous thread in Java. I think the reason you are seeing degraded performance is that your thread is very CPU/storage intensive. Try placing a sleep in there to slow the loop down and I would think the UI would become more responsive. – Erik Nedwidek Jan 21 '13 at 22:31
  • code seems to me correct..not sure why It is blocking UI in main thread. You should check other code too. – Jambaaz Jan 22 '13 at 05:34

2 Answers2

0

You are not using an AsyncTask - which is the control Android uses to do long running processes off the UI thread.

Bottom line, use this and you will have much more success.

AsyncTask Android example

Community
  • 1
  • 1
Booger
  • 18,579
  • 7
  • 55
  • 72
0

Use Handler to or .runOnUiThread(runnable) to call your UI thread. You can execute your thread without the Runnable as well, like this:

new Thread(){
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                Log.d("asdf", "asdf");
            }
        }
    }).start();
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148