简体   繁体   中英

Android - How to run multiple periodic handlers, simultaneously

I have a screen with multiple progressbars. I'm trying to run them all periodically, at the same time.

I originally did this like so (handler runs on the UI thread):

// Timers and Handlers for each of the 45 progressbars on screen. 
private Timer[] timer = new Timer[45];
private Handler[] handler = new Handler[45];
private boolean endTimers = false; 
private Handler handlerHolder;
private int idx; 
private void initTimers(){
    for(int i=0;i<timer.length;i++){
        idx = i;
        handlerHolder = handler[i] 
        timer[i] = new Timer();
        handler[i] = new Handler();
        final int finalI = i;
        timer[i].scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                handler[finalI].post(new Runnable() {
                    @Override
                    public void run() {
                        if (endTimers){
                            return;
                        }
                        timerEvent(finalI);
                    }
                });
            }
        }, 0, 100);
    }
}

This works, however, I'm finding that the progressbars glitch sometimes, and I read that TimerTasks have lots of issues with android. I tried to rewrite my code with handlers only, but it would just result in an infinite loop on the first index in the for loop.

My Attempt

private Runnable actionRunnable = new Runnable() {
    @Override
    public void run() {
        if (endTimers){
            return;
        }
        timerEvent(idx);
        handlerHolder.postDelayed(actionRunnable, 100);
    }
};

Then instead of the timer[i].scheduleAtFixedRate block above, I write

handler[i].postDelayed(actionRunnable, 100);

I understand why this creates an infinite loop ... but I'm not sure what I should do keep this handler running, but continue with the for-loop, like the the original way I did it.

I'd like for all my handlers in handlerArray to run periodically, all at the same time. Any advice is greatly appreciated.

Handler.post() executes the given Runnable on the thread which created the Handler. You are probably creating all the Handlers on the UI thread. This is no different than running the code directly. You need to create threads to the time consuming tasks. You can either do this directly with Threads or you can extend AsyncTask. The later is preferable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM