哪种Thread方法更适用于keepalive线程?

时间:2014-02-22 05:47:59

标签: android

我有一个项目,需要Android设备每30分钟将Android数据库Sqlite同步到服务器,我想创建一个线程将JSON发布到php页面,并且php页面会将数据插入/更新到Server,
在我阅读了关于线程文章的Android官方页面后,Android建议使用 执行者,ThreadPoolExecutor和FutureTask 线程,我需要线程keepalive直到关闭应用程序

问题:在这个项目中使用哪种线程方法?请提供一些示例代码

这是我在Android官方网站上找到的信息:

http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

执行人:http://developer.android.com/reference/java/util/concurrent/Executor.html

ThreadPoolExecutor:http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html

FutureTask:http://developer.android.com/reference/java/util/concurrent/FutureTask.html

1 个答案:

答案 0 :(得分:3)

首先,android已经内置了对Data Syncronization的支持,请查看Sync Adapters。尝试使用这个内置支持的类来检查Network Connectivity和设置定时器,以便在固定时间后运行同步等。

如果您不想尝试手动方式。

处理线程可能会成为开销。您可以使用Service OnCreateOnDestroy内启动应用,并销毁UI上的服务。有多种服务可以与Network Speed进行通信。看看Android Services

为什么我认为服务是因为,必须在后台完成同步,这可能需要更长的时间段基于Server response和{{1}}。通过服务可以轻松处理长时间的操作。