I would like to display a white rectangle periodically on the android screen; or change the background color. For example, every 500ms I want the screen color to change from black to white, for around 200ms, then back to black.
What is the best way to do this? I did try with an asynctask, but got an error that only the original thread can touch the View. I have a similar asynctask which sounds a periodic tone and that works fine.
SOLUTION:
With help from the responders I resolved my issue by creating two timers one for black and one for white. The black one starts delayed by the duration that I want to display the white screen. Both have the same execution rate, thus the white screen is displayed then, after duration ms the black screen is displayed. For example, the screen is black but flashes white every second for 200 ms.
@Override
protected void onResume() {
super.onResume();
mBlackTimer = new Timer();
mBlackTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
view.setBackgroundColor(Color.parseColor("#000000"));
}
});
}
}, duration, (long) (1000 / visionPeriod));
mWhiteTimer = new Timer();
mWhiteTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
view.setBackgroundColor(Color.parseColor("#ffffff"));
}
});
}
}, 0, (long) (1000 / visionPeriod));
}
AsyncTask is mainly used to perform background thread activity like downloading data from remote server. It runs on it's own thread that's why when from the AsyncTask you try to access any View of your Activity it gives that Error
that only the original thread can touch the View
.You may use Timer class or AlarmManager class for repetitive tasks. Visit my previous answer.