Android Asynctask vs Runnable vs timertask vs Service

shafqat picture shafqat · Nov 30, 2010 · Viewed 10.9k times · Source

What are the differences between these methods (classes)?

I want to run a app that runs every 5 seconds, clear the memory when it is finished and when the cpu is in standby mode, that you can run the app. So that the app is not bound to a wakelock.

Regards,

Shafqat

Answer

Sander Versluys picture Sander Versluys · Aug 14, 2011

The difference between first three is just the amount of work that has been done for you. And a Service is a fundamental Android application component.

AsyncTask as a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.

The Runnable interface is at the core of Java threading. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

TimerTask is part of standard Java and can be use for delayed or repeated execution for some piece of (Runnable) code. It's use is discouraged on Android. You can use a Handler instead.

A Service can be used as a independent and UI-less part of your Android application. It can run and create it's own threads and can be started for UI or with Intents through a AlarmManager for example.

It think want you want is a Service which creates it's own thread and does some work. When the work is done, memory will be freed on Android when the garbage collector kicks in, something you do not control and that's a good thing.

The AlarmManager allows you to broadcast Intents at specified intervals and even allow control to wake-up the device or not. You just have to define a BroadcastReceiver in your Service and declare it in your manifest.

The last part of your question I don't really understand, so please clarify a bit more on what your trying to accomplish.