Android Asynctask vs Runnable vs timertask vs Service

喜欢而已 提交于 2019-12-02 20:38:47

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!