1
timer = new Timer("Timer Thread");

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
                showDialog(0);
                timeBar.setProgress(time);
            }
        }
    }, INTERVAL, INTERVAL);`

My onCreateDialog method is working fine, so when I use showDialog(0) from a Button it works fine. But not if the method is called by a Scheduler.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
barata7
  • 338
  • 1
  • 5
  • 13

2 Answers2

6

Using a handler:

protected static final int DIALOG_OK= 0;

timer = new Timer("Timer Thread");

timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
            mDialogHandler.sendEmptyMessage(DIALOG_OK);
            timeBar.setProgress(time);
        }
    }
}, INTERVAL, INTERVAL);

 private Handler mDialogHandler = new Handler(){
            public void handleMessage(android.os.Message msg) {
                    switch (msg.what) {
                    case DIALOG_OK:
                            // We are now back in the UI thread
                            showDialog(0);
                    }

            };
    };

This allows you to call method's on the UI thread from other threads. Need more explanation, just ask.

Blundell
  • 75,855
  • 30
  • 208
  • 233
3

You need to call these methods on the UI thread.

One way to do this is via AsyncTask, as in this answer.

Another way is to create a Handler and send messages to it from your TimerTask.

You can read more about AsyncTasc and the UI thread in Painless Threading.

Community
  • 1
  • 1
Matthew
  • 44,826
  • 10
  • 98
  • 87