Android schedule fast task

321 Views Asked by At

I have a problem with events schedulation. I need to change text color every fixed time. Range of this is between 100ms and 300ms. I've tried to use Android Timer - TimerTask but after 10-15 Thread the rendering is delayed then I lost real time update. I've tried also to use Thread.sleep() but I've had an exception with MainThreadActivity. Timer problem I think that is JVM Thread allocation or at most a concurrency problem. I asked you what is the best way for scheduling fast event with fixed delay in Android and if my approach is correct.

Thank you in advance.

Fabio

2

There are 2 best solutions below

4
Denys Vasylenko On

Try something like this:

final static int REFRESH_TIME_MS = 100;
final static int REFRESH_TIME_MS_2 = 200;

Runnable mPeriodicTask = new Runnable() {
    public void run() {
        //do what you want
    }
};

Runnable mPeriodicTask_2 = new Runnable() {
    public void run() {
        //do what you want
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    executor.scheduleAtFixedRate(mPeriodicTask, 0, REFRESH_TIME_MS, TimeUnit.MILLISECONDS);
    executor.scheduleAtFixedRate(mPeriodicTask_2, 0, REFRESH_TIME_MS_2, TimeUnit.MILLISECONDS);
}
5
Pasquale Anatriello On

Try the CountDownTimer. It's executed on the UI Thread and gives you information on exactly how much time passed since the last invocation. Adding an example to be more clear: Let's say you want to update the view after 300 ms ,150 ms and 75 ms that makes the total time 525ms and the minimum interval 50ms

so:

    private class TestCT extends CountDownTimer{

            private long mFirstTime;
            private long mTotalTime;
            private long mLastRecognizedEvent=0;

            public TestCT(long millisInFuture, long countDownInterval, long firstEventTime) {
                super(millisInFuture, countDownInterval);
                mTotalTime=millisInFuture;
                mFirstTime=firstEventTime;
            }

            @Override
            public void onTick(long millisUntilFinished) {
                long elapsed=mTotalTime-millisUntilFinished;
                elapsed-=mLastRecognizedEvent;
                if(elapsed>=mFirstTime){
                    updateTheView();
                    mLastRecognizedEvent+=mFirstTime;
                    mFirstTime=mFirstTime/2;
                }
            }

            @Override
            public void onFinish() {
                updateTheView();

            }


        }

new TestCT(525,50,300).start();

Not tested this so not 100% sure will work but it should give you an idea