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));
}
You can use timer class for this to perform some task on repeated interval:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
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.
Create a Timer task method and inside the timertask and give it a periodic duration of 700ms show the black background and then create a handler for showing white background and post delay it for 500ms
try all of this in the uithread only
don't use new thread or asynctask
like this:
mTimer = new Timer();
mTtask = new TimerTask() {
public void run() {
//set your black background here
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// set your white background here
}
}, 500);
}
};
mTimer.schedule(mTtask, 1, 700);
Related
I want to create a flashing effect by drawing a path with color grey, white (matching to the background), and then grey again. I want to flash 3 times, showing gray for 1 sec, white for 1 sec gray again for 1 sec, etc.
When I created a Handler for postDelayed(), the program skipped over the run() and did not execute it in the timing set, and no flashing occurred:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
invalidate(); //calls onDraw()
Log.d(TAG, "Flashing now now");
}
}, 1000);
How would I implement such a flashing functionality with a timer and flash it 3 times?
Thanks!
You can try something like this,
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("done}
}, delay, period);
Otherwise you have plenty other examples to follow like this Example 1, Example 2, Example 3 etc. Let me know if you still need help.
This is a working code example of how we flash a globe from blue to red and back again. You can modify the code on the inside to limit how many times and what time delay you want.
protected MyGlobeFlasherHandler handlerFlashGlobe = new MyGlobeFlasherHandler(this);
#Override
protected onCreate(Bundle bundle) {
handlerFlashGlobe.sendEmptyMessageDelayed(0, 700);
}
/**
* private static handler so there are no leaked activities.
*/
protected static class MyGlobeFlasherHandler extends Handler {
private final WeakReference<HomeBase> activity;
public MyGlobeFlasherHandler(HomeBase activity) {
this.activity = new WeakReference<HomeBase>(activity);
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (activity.get() != null) {
if (activity.get().shadedGlobe) {
activity.get().imgData.setImageDrawable(activity.get().getResources().getDrawable(R.drawable.globe_blue));
} else {
activity.get().imgData.setImageDrawable(activity.get().getResources().getDrawable(R.drawable.globe_red));
}
activity.get().shadedGlobe = !activity.get().shadedGlobe;
sendEmptyMessageDelayed(0, 700);
}
}
}
I am new in android and so, I need your help.
I want new and refreshed values in edit box such that after every 10 seconds without button click it brings changed value of PLC on edit box in my android device.
try this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
edittext.settext(yourtext);
}
}, 10000);
You can do this with a Timer for example. But think abaout, that this what You want to do is a Little bit battery intensive :
//create a Timer and TimerTask
private Timer timer;
private YourTimerTask yourTimerTask;
private void activateTimer(){
if(timer!=null){
timer.cancel();
}
timer = new Timer();
yourTimerTask = new YourTimerTask();
//this timer starts after 1 second and repeats every 10 seconds
timer.schedule(yourTimerTask, 1000, 10000);
}
private class YourTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable(){
#Override
public void run() {
yourEditBox.setText(yourText);
}});
}
}
I think with Edit box You mean an EditText? Anyway, this example is not tested, just from scratch. But it should give You an idea how to do.
I simply want to change the bitmap image of an imageview on a set interval ( 2 seconds)
I have tried this but the app crashes:
private void prefromRadarInterval() {
int delay = 1000; // delay for 0 sec.
int period = 1000; // repeat every 1 seconds.
timer = new Timer();
timer.scheduleAtFixedRate(new SampleTimerTask(), delay, period);
}
public class SampleTimerTask extends TimerTask {
#Override
public void run() {
//MAKE YOUR LOGIC TO SET IMAGE TO IMAGEVIEW
imageview_radarcurrent.setImageBitmap(radar_animation[flag]);
flag++;
if(flag > 9) {
flag = 0;
}
}
}
The log cat prints this:
01-12 04:51:51.688: E/AndroidRuntime(19688): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Help and explanation would be appreciated!
Your problem is that the UI can only be modified buy the UI thread, and your TimerTask is running on it's own thread. The easiest way to solve this is probably by posting through a handler to the UI thread.
Take a look at this thread:Android timer updating a textview (UI)
You should call the setImageBitmap() from the UI thread.
For example:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// Write your code here
}
});
... or post it with a Runnable:
imageview_radarcurrent.post(new Runnable() {
#Override
public void run() {
}
});
Im trying to get an ImageSwitcher to change an image every 5 secs..
I tried using a Timer:
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
},0,5000);
But I get this error:
LOGCAT:
12-14 15:07:29.963: E/AndroidRuntime(25592): FATAL EXCEPTION: Timer-0
12-14 15:07:29.963: E/AndroidRuntime(25592): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
runOnUiThread(new Runnable() {
public void run() {
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
}
},0,5000);
Only the original thread that created a view hierarchy can touch its views.
Timer task runs on a different thread. Ui should be updated on the ui thread.
Use runOnUiThread.
runOnUiThread(new Runnable() {
public void run() {
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
You can also use Handler instead of timer.
Edit:
Check this setBackgroundResource doesn't set the image if it helps
in one of my Activities I want to keep screen on for 2 minutes (e.g.). I know I can keep screen on with:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
but how to do that for an specific duration ?
You have many ways to clear flags after 2 minutes..like you can use timer or thread or handler
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}, 20000);
in this way you can clear the flags
Take this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// turn screen off function
}
}, 2000);
After 2sec it will turn off the screen. You just have to put the turn off function in it.
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
// start your screen
}
}, 2000); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called