Handler.postDelayed(Runnable) vs CountdownTimer - android

Sometimes we need to delay a code before it runs.
This is doable by the Handler.postDelayed(Runnable) or CountdownTimer.
Which one is better in terms of performance?
See the sample code below
Handler
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//DO SOMETHING
}
}, 1000);
CountDownTimer
new CountDownTimer(1000, 1000) {
public void onFinish() {
//DO SOMETHING
}
public void onTick(long millisUntilFinished) {}
}.start();

The Handler should offer you better performances as CountDownTimer contains itself a Handler as you can see here.

I agree that Handler is offering a better performance. But on a side note, you should keep in mind that CountDownTimer object will be destroyed after completed. A Handler will continue to exist after finished. If you only need a temporary timer then CountDownTimer is preferable. Otherwise, use a Handler.

Use Handler,Android Handler is Good.
See Here, What Others say About Handler

Related

How can i handle my Looper in an OnClick method to run a function with delay?

I would like to be able to run my specific method in background through a looper in an on click event, is this the right way to do this?
myThread = new LooperThread();
myThread.start();
upload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myThread.handler.post(new Runnable() {
#Override
public void run() {
//my methods
}
});
}
});
And my Looper Class:
class LooperThread extends Thread {
Handler handler;
public void run() {
Looper.prepare();
handler = new Handler();
Looper.loop();
}
}
If it is,
the problem is that in this way, i don't understand why the system don't recognize "handler" while i typing: "myThread.handler.post.." and run the methods.
Otherwise, can you help me on making this?
I am sorry if i made mistakes while making the question, but it's my first time here :)``
Welcome to Stack Overflow.
I would like to be able to run my specific method in background through a looper in an on click event, is this the right way to do this?
Your code works, but I couldn't say it's the right way to do it. Like #tynn mentioned, a HandlerThread might be a better option.
If it is, the problem is that in this way, i don't understand why the system don't recognize "handler" while i typing: "myThread.handler.post.." and run the methods.
Otherwise, can you help me on making this?
If I understood your problem, it's an access issue. Your handler seems unaccessible since it's declared as package-private. You could make your handler visible this way:
// Should this class be public or package-private?
public class LooperThread extends Thread {
private Handler handler;
public Handler getHandler() {
return handler;
}
// ...
}
And you will be able to reference the handler like this:
myThread.getHandler().post(...);
UPDATE
You can delay a Runnable execution this way:
// Delay execution of a Runnable task by 5000 milliseconds.
myThread.getHandler().postDelayed(myDelayedRunnable, 5000);

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 Async, Handler or Timer?

Every 5 seconds, I want to call my webservice and get text (not images), then display it in my ImageAdapter. What would be the best way to accomplish this?
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
callWebservice();
}
};
handler.postDelayed(r, 5000);
It depends if you want to use a different thread or not. Do you want the user to be able to interact with the application on the UI Thread while the images are downloading? If so, then I would definitely use an AsyncTask with a small ProgressBar (style="#android:style/Widget.ProgressBar.Small")
If you don't care about threading then what #inazaruk said.
Edit: the truth is most modern apps that retrieve data from a web service will use an AsyncTask with a discreet little loader in the corner just to let the user know it's updating.
Edit 2: here's an example of using a TimerTask to run something every 5 seconds. The key is the runOnUiThread(). There may be better ways to tie all the elements together but this accurately portrays all the pieces.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
CallWebService();
}
}, 0, 1000);
}
private void CallWebService()
{
this.runOnUiThread(fetchData);
}
private Runnable fetchData = new Runnable() {
public void run() {
asyncTask.execute();
}
};
You should call asynctask inside the application main thread. Asynctask can't be called in a background thread.

Android CountDownTimer

When writing :
CountDownTimer timer = new CountDownTimer(1000, 100)
{
#Override
public void onTick(long l)
{
}
#Override
public void onFinish()
{
};
}.start();
are we actually starting a new thread that handles ticks? If not, what is really happening?
CountDownTimer's implementation uses Handler and sendMessageDelayed(), so no background thread is needed. This does mean that the timer will not update if you are tying up the main application thread elsewhere in your code.
Definition from multiple publications, tried and tested:
"Another timer is provided with the built-in class CountDownTimer.This encapsulates the creation of a background thread and the handler queuing into a convenient class call..."

Categories

Resources