Get remaining time when using handler.postDelayed - android

I am using handler.postDelayed method to create some delay for some animation stuff.
Like this:
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// Start Animation.
}
}, 6000);
Later, How can I get the remaining time until the animation starts?

You can simply save the time in a var when you call post delayed
long startTime = System.nanoTime();
h.postDelayed(...
and then when you need to check the remaining time you can calculate the elapsed time like
long elapsedTime = System.nanoTime()-startTime;
So in your case
long remainingTime = 6000 - elapsedTime;

Related

Add a delay before playing an audio using Android MediaPlayer

I want to play 5 audio's at a go but with different time delays. Like (a.mp3 with a time delay of 2 sec, b.mp3 = 4 sec etc) but i dont know how to do it.
You can use handler.
Handler handler = new Handler();
final static int DELAY = 1000; // one second
public void playAudioWithDelay(){
handler.postDelayed(new Runnable(){
//your code start with delay in one second after calling this method
}, DELAY);
handler.postDelayed(new Runnable(){
//your code start with delay in two seconds after calling this method
}, DELAY * 2);
}

Running for loop periodically

I want to run a for loop every 5 minutes for an Android application. Is there a better method than this where less processing is done
for(;;) {
// code
final long NANOSEC_PER_SEC = 1000 * 1000 * 1000;
long startTime = System.nanoTime();
while ((System.nanoTime() - startTime) < 5 * 60 * NANOSEC_PER_SEC) {
}
}
CountDownTimer is a good class for this kind of work. It looks like this:
long duration = 12345;
long ticksInterval = 5000; // 5 second in millis
new CountDownTimer(duration, ticksInterval){
public void onTick(long remaining) {
// Do something each ticksInterval millis
}
public void onFinish() {
// Do something after duration millis
}
}.start();
That said, I don't think you can use this for an infinite amount of time since it requires an ending time. Though you can hack to restart it once it's finished.
You should go for set Repeat Alert for every 5 Minute and Run your code inside that .
Also you can go for use of Handler like below code .
final int REPEAT_CALL=2;
final int mFIVE_MINUTE=5*60*1000;
private Handler mHandler=new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
case REPEAT_CALL:
//This will get execute by every 5 minute so write you for loop code here.
mHandler.sendEmptyMessageDelayed(REPEAT_CALL,mFIVE_MINUTE);
break;
}
}
};
You can start it by calling this :
mHandler.sendEmptyMessageDelayed(REPEAT_CALL,10);
Then after it will call by every 5 minute .
You can cancel this call back by calling below method:
mHandler.removeMessages(REPEAT_CALL);

Unique Timer for saving(SharedPreferences) elapsed time in activity

as always Thanks for reading and thinking on this question.
I want to save elapsed time in some activities and using them later, i thought SharedPreferences would be a good choice for saving, but i found Using Chronometer not efficient. I'll appreciate any help. thanks.
Declare your variable:
long lastTimeRecorded;
Then in onCreate get a start time:
lastTimeRecorded = System.currentTimeMillis();
Then when you update the time call this function from the activity:
public void updateTimer(){
long elapsedTime = System.currentTimeMillis() - lastRecordedTime;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putLong("elapsedTime", elapsedTime);
}
If you want it to repeat at certain intervals:
private final int interval = 1000; // in millis
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
public void run() {
updateTimer();
}
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);
From samuel, here
How to set a timer in android

Automatically refresh image every 2 seconds android

So I am trying to have a picture automatically refresh every 2 seconds. I've tried the handler/timer method, but I'm confused as how to call it and for some reason can not get it to actually refresh...
private void refreshPicture(final String refreshRate, final String userName, final String userPicture) {
final Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = Long.parseLong(refreshRate);
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
//my method where i refresh image
getUserPicture(userName, userPicture);
timerHandler.postDelayed(this, 500);
}
};
}
You forgot to initiate the first call of the runnable. After defining the timerRunnable, you have to call timerHandler.post(timerRunnable); once. Also, if you want to have it refreshed every 2 seconds, you have to put 2000 instead of 500 as value in postDelayed().
Don’t forget to call timerHandler.removeCallbacks(timerRunnable) when you want to stop refreshing.

How to change a TextView every second in Android

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/

Categories

Resources