Android compare to a time to current time continuously - android

I am making an app which need to compare two date and time continuously.
I just saw some example which just compare once. I think I can use timer to repeat a method but it seem not very efficient. Anyone did this before?

Maybe you can use postDelayed like below.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
compareTime();
}
}, 5000);
replace 5000 with your own interval milliseconds.

It is easy, you can use handler; When the first time to check time send the normal message like this
mHandler.sendMessage(mHandler.obtainMessage(CHECK_TIME);
Afterwards sendDelayedMessage from inside the handler.
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case CHECK_TIME:
// Your compare time code here
// ....
// Send the delayed message to handler to check time again
mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_TIME),
DELAY_CHECK_TIME_INTERVAL);
break;
}
}
}

Related

Stopping and restarting timer

I'm using a pageslider and timer for it. I wrote a timer method for this pageslider such:
public void setTimerToSlider() {
sliderTimer = new Timer();
sliderHandler = new Handler();
sliderTimerTask = new TimerTask() {
#Override
public void run() {
sliderHandler.post(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem()<images.length-1) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
};
sliderTimer.scheduleAtFixedRate(sliderTimerTask, 0, sliderTimeOut*1000);
}
When user slides it manually, timer goes on. So, for example, if 1 second remains, when user slides, it goes to next in 1 second.
My aim is that when user slides it manually, it resets the remaining time and starts the time out from 0.
Are you asking how to cancel the current timer and start a new one each time there's user input?
You allocated a Handler. Use that for your timing instead of a Timer. Handlers are more useful on Android, e.g. the Activity lifecycle knows what to do with them. They might use less battery power, too.
When a new user input event arrives, call sliderHandler.removeMessages(MSG_PAGESLIDER) to cancel any previous timers, then call sliderHandler.sendEmptyMessageDelayed(MSG_PAGESLIDER, 1000), where:
static final int MSG_PAGESLIDER = 1;
class UpdateHandler extends Handler {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_PAGESLIDER:
// react to the timeout; schedule another message if desired
break;
}
}
}
UpdateHandler sliderHandler = new UpdateHandler();
aaaaaannnnnnnnd your question is? ( not my downvote, btw, but we tend to follow a question-answer format )
=]
Consider referencing the Calendar, it goes down to the millisecond and is not as susceptible to delays f'ing up your game
Calendar calendar = Calendar.getInstance();
http://developer.android.com/reference/java/util/Calendar.html
gl hf

How can I create timer tick in Android?

I have this method
public void GetSMS(){
//in this method I read SMS in my app inbox,
//If have new SMS create notification
}
for this I think create timer tick method and every 5 sec call GetSMS()
How can I create a correct method for that ?
Here is an example of Timer and Timer Task. Hope this helps.
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// Do whatever you want
}
});
}
};
timer.schedule(timerTask, 1000); // 1000 = 1 second.
Maybe with a timer and a timertask?
See javadocs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
Yet receiving broadcasts is probably a more solid solution.
See: Android - SMS Broadcast receiver
Use Timer.scheduleAtFixedRate() as follow:
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
GetSMS();
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 5000, 5000); // every 5 seconds.
I saw it by accident.. This is not the right way to do it..
You don't need to check if there is a sms that received. Android provide broadcast receiver to get notified when sms is income.
Here you go, you have the link here.. Copy paste and it will work great
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87
Hope that this make sense
Although the above timer methods are the correct way to use timers of the sort you are after, I quite like this little hack:
new CountDownTimer(Long.MAX_VALUE, 5000)
{
public void onTick(long millisUntilFinished)
{
// do something every 5 seconds...
}
public void onFinish()
{
// finish off when we're all dead !
}
}.start();
Long.MAX_VALUE has, according the Java docs, a (signed) value of 2^63-1, which is around 292471 millennia ! So starting up one of these countdown timers effectively lasts forever relatively speaking. Of course this depends on your interval time. If you want a timer every 1 second the timer would "only" last 58494 millenia, but we don't need to worry about that in the grander scheme of things.

Refresh parsing code android

I am using the JSON parser to parse some pages but I would like to recall the parsing function every 30 seconds. How can i do that ?
One of the method to call a method every 30 seconds is by using postDelay of Handler see below code.
Handler handler;
handler=new Handler();
handler.removeCallbacks(run);
handler.post(run);
Runnable run=new Runnable()
{
public void run()
{
parsing();
handler.postDelayed(run,30000);
}
};
Another approach is by using "AlarmManager"
That is a weird need, only parsing when necessary would probably be a lot better.
Anyway, you should have a look at Timers and background services but be sure of what you are doing : if you create a background service that make a network call twice every minute, if that call is costly, you could cost a lot of data and/or battery to your users which is not a good idea.
You can do it using a timer.
Timer myTimer = new Timer();
After that you can call use the schedule method to call your json parser method.
myTimer.schedule(new TimerTask()
{
public void run() {
timerMethod();
}
}, 0, 1000);
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}

Android jodatime, is it possible to execute a piece of code after set duration?

What would be the best way to run a piece of code, lets say every minute? Using jodatime..
How would I do that?
Would not like to use Timer.
You don't even need jodatime:
private final Handler handler = new Handler();
final Runnable code = new Runnable() {
#Override
public void run() {
// do something
// then queue the runnable again
Outerclass.this.handler.postDelayed(code, 60000L);
}
};
// ...
this.handler.postDelayed(this.gpsNotUpdatingCheck, 60000L); // delay one minute
Here is more information: http://developer.android.com/reference/android/os/Handler.html

How to cancel a handler before time in Android code?

I create 1 minute delayed timer to shutdown service if it's not completed. Looks like this:
private Handler timeoutHandler = new Handler();
inside onCreate()
timeoutHandler.postDelayed(new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
}, 60 * 1000);
If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.
You can't really do it with an anonymous Runnable. How about saving the Runnable to a named variable?
Runnable finalizer = new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
};
timeoutHandler.postDelayed(finalizer, 60 * 1000);
...
// Cancel the runnable
timeoutHandler.removeCallbacks(finalizer);
If you don't want to keep a reference of the runnable, you could simply call:
timeoutHandler.removeCallbacksAndMessages(null);
The official documentation says:
... If token is null, all callbacks and messages will be removed.
You might want to replace use of postDelayed with use of sendMessageDelayed like so:
private Handler timeoutHandler = new Handler(){
#Override
public void handleMessage(Message msg)
{
switch (msg.what){
case 1:
((Runnable)msg.obj).run();
break;
}
}
};
Then post a Message:
Message m = Message.obtain();
m.what = 1;
m.obj = new Runnable(){
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
};
timeoutHandler.sendMessageDelayed(m, 60 * 1000);
and then cancel:
timeoutHandler.removeMessages(1);
No tracking of the runnable necessary.
If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.
Use Handler.removeCallbacks(yourRunnable).

Categories

Resources