I got a fragment which got a control called RingProgress which is simply a ring that fills itself according to a percentage value given. For example, if I do:
ringProgress.setProgress(20);
It means that 20% of the ring will now be filled.
What I'm trying to do is to animate the ring being filled over a few seconds. So what I've tried to do is this:
#Override
public void onResume()
{
super.onResume();
HandlerThread handlerThread = new HandlerThread("countdown");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable()
{
#Override
public void run()
{
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
int totalSeconds = secondsToStart + minutesToStart * 60;
int secondsPassed = 0;
#Override
public void run()
{
if(secondsPassed == totalSeconds)
{
timer.cancel();
}
final int currentProgress = (secondsPassed / totalSeconds) * 100;
secondsPassed++;
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
mRingProgressBar.setProgress(currentProgress);
}
});
}
}, 0, 1000);
}
});
}
The problem is that the update of the ring is not shown until the time is up. For example, if I set it for 5 seconds then when the fragment loads the ring is set to 0, then nothing happens for 5 seconds and then the ring is full with 100% all at once..
How can I start this animation properly?
I guess the problem is with
final int currentProgress = (secondsPassed / totalSeconds) * 100;
secondsPassed / totalSeconds return int value so it will be 0 or 1 only. And you multiply it to 100.
You have to use float or double instead
something like
final int currentProgress = Math.round(((float) secondsPassed)/((float) totalSeconds)*100f);
On this line:
Handler handler = new Handler(handlerThread.getLooper());
You are trying to get the looper from a handlerThread. But how sure you are the looper has already been initialized?
From the documentation of getLooper()
This method returns the Looper associated with this thread. If this thread not been started or for any reason is isAlive() returns false, this method will return null. If this thread has been started, this method will block until the looper has been initialized.
onLooperPrepared() is the callback, where you can be sure, that the Looper has been initialized, and therefore you can construct logics on that.
Thus, what you have to do, is to subclass HandlerThread and create appropriate logics from onLooperPrepared() callback.
Here's a nice post which will help you out. See implementation of MyWorkerThread class there.
Instead of using a handler, you could use a property animator as follows:
ObjectAnimator.ofInt(mRingProgressBar, "progress", 0, 100)
.setDuration(totalSeconds * 1000) //time is in miliseconds
.start();
This will find a method setProgress() in your mRingProgressBarand set the value according to the limits given. In the example above, 0 to 100.
You can read more about it here
Since you want to run on a different thread, you can use this handler in the top of the class:
private int progress = 0;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
ringProgress.setProgress(progress);
progress += 20;
if (progress == 100) { //clear??
}
timerHandler.postDelayed(this, 1000);
}
};
In inCreate set the max:
ringProgress.setMax(100);
This will complete the animation within 5 seconds, then you can clear the animation. If you want smaller increments, change the line below (update every tenth of a second), and change the steps
timerHandler.postDelayed(this, 100);
Related
I know how to use handler and runnable to call a method at regular intervals of time. But now I want to call more than one method at regular interval of time. Below is the code in one of my classes:
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
for(int index = 0; index < count; index++) {
//Do something based on the index value
}
handler.postDelayed(runnable, 500);
}
};
Somewhere in my code I will have the below code to start the execution:
handler.postDelayed(runnable, 0);
So the first method corresponding to index 0 will be called first followed by other methods. And then there will be a 500ms delay to repeat the same.
But I also want a 500ms delay between the method calls. I mean when the for loop is executed. How can I do it using only one handler and runnable? How can I induce a 500ms delay between the method calls?
I would update the value of index across Handler invocations myself, and compare it to yourcount variable just like the for loop
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
private int index = 0;
#Override
public void run() {
//Do something based on the index value
index++;
if (index < count) {
handler.postDelayed(runnable, 500);
} else {
count = 0;
}
}
}
Besides, at the start you don't need to invoke postDelayed() with zero delay, you can directly call post().
Hello I'm trying to delay imageviews to give a perception that they are being taken out one by one. I've tried
Thread.Sleep
CountDownTimer
Runnable/Handler
But they either only delay once and both imageviews change at the same time or do not delay at all. For some reference I'm trying to do something like
private void delaycard(final int Card) {
newcard(Card); //Delay this before it is called
}
Willing to try/retry anything at this point
Off the top of my head, try something like this:
Handler h = new Handler();
//for the number of images we have
for (int i = 0; i < numImages; i++) {
//we create a runnable for that action
Runnable r = new Runnable() {
#Override
public void run() {
newCard(card);
}
};
//this is the amount of time to delay it by
delay = delay + 500;
//effectively, we're creating a series of runnables at the same time
//but they activate one after the other in .5s intervals
h.postDelayed(r, delay);
}
put this inside your method
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
newCard(Card);
}
}, 100);
EDIT: Code works now. I ended up calling loadingIllusionLoader() from within createDialog()...
I am trying to get a 'fake' progress bar to show up once a user presses a button. I want the progress bar to appear for some random time ~ 2000ms and then have a Dialog box appear as well as hiding the progress bar (because it 'loaded').
I was told to try and use handler since Thread.sleep locks up the UI, which I dont want to really do. However, once I execute the code below, it runs the handler's postDelayed function and a new Dialog box appears every moment or so... the handeler is executing itself over and over again. How do I STOP the handler. the removeCallbacksAndMessages function on the handler was an option, but Im not sure how to exactly STOP the Dialog boxes from opening.
public void loadingIllusionLoader()
{
ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
theCircleLoader.setVisibility(View.VISIBLE);
int timeToRest = (int) (Math.random() * 1000) + 1500;
final Handler newHandle = new Handler();
newHandle.postDelayed(new Runnable() {
#Override
public void run() {
createDialog();
hidingIllusionLoader();
newHandle.removeCallbacksAndMessages(null);
}
}, timeToRest);
}
public void hidingIllusionLoader()
{
ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
theCircleLoader.setVisibility(View.INVISIBLE);
}
I think you'd rather want to use a CountDownTimer:
CountDownTimer timer = new CountDownTimer( 10000, 1000 ) {
#Override public void onTick( long millisUntilFinished ) {
theCircleLoader.setProgress( theCircleLoader.getProgress() - 1 );
}
#Override public void onFinish() {
theCircleLoader.setVisibility(View.INVISIBLE);
}
};
EDIT: almost forgotten:
timer.start();
EDIT2:
after looking at your code, I suggest you modify it so:
Random rnd = new Random();
int progressBarMax = rnd.nextInt( 10 ) + 1; // 10 - change it the way you like
int timeToRest = progressBarMax * 500;
theBarLoader.setMax( progressBarMax );
theBarLoader.setProgress( 0 );
CountDownTimer theTimer = new CountDownTimer(timeToRest, 500)
{
#Override public void onTick( long millisUntilFinished ) {
theBarLoader.setProgress( theCircleLoader.getProgress() + 1 );
}
#Override public void onFinish() {
theCircleLoader.setVisibility(View.INVISIBLE);
// theBarLoader.setVisibility(View.INVISIBLE);
createDialog();
}
};
theTimer.start();
This question already exists:
Timer time does not change as variable?
Closed 9 years ago.
I have to call some webservice method in variable times, every time method runs it returns me next period time as long. I tried it with timer but after first calling, it can not understand new variable time.
This is the link asked yesterday something about it: Timer time does not change as variable?
Here is the sample code:
private int V_Time = 1;
.
.
.
try {
final Timer V_Timer;
final Handler V_Handler;
V_Timer = new Timer();
V_Handler = new Handler(Looper.getMainLooper());
V_Timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
V_Handler.post(new Runnable() {
public void run() {
webservice_method();
V_Time = 2; // it returns from method, not manually right as shown
//and it can be change every time method calls..
}
});
}
}, 0, V_Time * 1000 * 60);
} catch (Exception hata) {
}
It works first time after 1 minute, but others does not change (eg 2 min), it works every 1 minute.
I want just it works properly, with timer or without timer with anything else...
I think I may cancel timer but I guess I cannot resume or restart it again.
It must be something to do what I want, but I do not to know how?
I want to change period time, every timer task run what return from method.
What you are trying to achieve is impossible. You have to cancel the current task and reschedule a new one with the new interval.
private TimerTask mTask = new TimerTask() {
#Override
public void run() {
V_Handler.post(new Runnable() {
public void run() {
webservice_method();
V_Time = 2; // it returns from method, not manually right as shown
//and it can be change every time method calls..
V_Timer.cancel();
V_Timer.scheduleAtFixedRate(mTask, 0, V_Time * 1000 * 60);
}
});
}
}
try {
final Timer V_Timer;
final Handler V_Handler;
V_Timer = new Timer();
V_Handler = new Handler(Looper.getMainLooper());
V_Timer.scheduleAtFixedRate(mTask, 0, V_Time * 1000 * 60);
} catch (Exception hata) {
}
I've made a simple Android music player. I want to have a TextView that shows the current time in the song in minutes:seconds format. So the first thing I tried was to make the activity Runnable and put this in run():
int position = 0;
while (MPService.getMP() != null && position<MPService.duration) {
try {
Thread.sleep(1000);
position = MPService.getSongPosition();
} catch (InterruptedException e) {
return;
}
// ... convert position to formatted minutes:seconds string ...
currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
But that fails because I can only touch a TextView in the thread where it was created. So then I tried using runOnUiThread(), but that doesn't work because then Thread.sleep(1000) is called repeatedly on the main thread, so the activity just hangs at a blank screen. So any ideas how I can solve this?
new code:
private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
public void run() {
final int start = startTime;
int millis = appService.getSongPosition() - start;
int seconds = (int) ((millis / 1000) % 60);
int minutes = (int) ((millis / 1000) / 60);
Log.d("seconds",Integer.toString(seconds)); // no problem here
if (seconds < 10) {
// this is hit, yet the text never changes from the original value of 0:00
currentTime.setText(String.format("%d:0%d",minutes,seconds));
} else {
currentTime.setText(String.format("%d:%d",minutes,seconds));
}
timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
}
};
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService();
// start playing the song, etc.
if (startTime == 0) {
startTime = appService.getSongPosition();
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime,1000);
}
}
what about 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()
{
//your code
}
}, delay, period);
Use a Timer for this (instead of a while loop with a Thread.Sleep in it). See this article for an example of how to use a timer to update a UI element periodically:
Updating the UI from a timer
Edit: updated way-back link, thanks to Arialdo: http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html
Edit 2: non way-back link, thanks to gatoatigrado: http://android-developers.blogspot.com/2007/11/stitch-in-time.html
You have to use a handler to handle the interaction with the GUI. Specifically a thread cannot touch ANYTHING on the main thread. You do something in a thread and if you NEED something to be changed in your main thread, then you call a handler and do it there.
Specifically it would look something like this:
Thread t = new Thread(new Runnable(){
... do stuff here
Handler.postMessage();
}
Then somewhere else in your code, you do
Handler h = new Handler(){
something something...
modify ui element here
}
Idea its like this, thread does something, notifies the handler, the handler then takes this message and does something like update a textview on the UI thread.
This is one more Timer example and I'm using this code in my project.
https://stackoverflow.com/a/18028882/1265456
I think the below blog article clearly gives a very nice solution. Especially, if you are a background service and want to regularly update your UI from this service using a timer-like functionality.
It really helped me, much more than the 2007 blog link posted by MusiGenesis above.
https://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/