开发者

Android Dialog not showing at all if called from a Timer Task

开发者 https://www.devze.com 2023-02-16 09:10 出处:网络
timer = new Timer(\"Timer Thread\"); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() {
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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消