Sleep function in android program

Fredkr picture Fredkr · Dec 3, 2011 · Viewed 69.6k times · Source

Having some problem getting my program to sleep What im trying to do is when the btnStart is pressed firs randomly set pictures to 12 ImageButtons Then i want it to pause for 5 secs and then change the first ImageButton to another picture

My code looks like this, right now it pauses straight away when the button is pressed...

       btnStart.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View v) {
            // TODO Auto-generated method stub

            Collections.shuffle(pic);
            int time=1;
            press=true;

            pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.memgreen));
            pic.get(1).setImageDrawable(getResources().getDrawable(R.drawable.memgreen));
            pic.get(2).setImageDrawable(getResources().getDrawable(R.drawable.memred));
            pic.get(3).setImageDrawable(getResources().getDrawable(R.drawable.memred));
            pic.get(4).setImageDrawable(getResources().getDrawable(R.drawable.memblue));
            pic.get(5).setImageDrawable(getResources().getDrawable(R.drawable.memblue));
            pic.get(6).setImageDrawable(getResources().getDrawable(R.drawable.memwhite));
            pic.get(7).setImageDrawable(getResources().getDrawable(R.drawable.memwhite));
            pic.get(8).setImageDrawable(getResources().getDrawable(R.drawable.mempurple));
            pic.get(9).setImageDrawable(getResources().getDrawable(R.drawable.mempurple));
            pic.get(10).setImageDrawable(getResources().getDrawable(R.drawable.memyellow));
            pic.get(11).setImageDrawable(getResources().getDrawable(R.drawable.memyellow));

            try {
                Thread.sleep(5000);

                pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.coin));

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     }
  });

Answer

Craigy picture Craigy · Dec 3, 2011

Well, if you want the UI to remain responsive you can't block the UI thread with Thread.sleep there.

Create a new thread, then sleep it. After the sleep, run the method for changing the view drawable on the UI thread

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.coin));
            }
        });
    }
}).start();