Using an AsyncTask inside a Service Class?(在服务类中使用 AsyncTask?)
问题描述
我必须将数据上传到服务器.我正在使用与我的应用程序在同一进程上运行的服务.我应该使用单独的线程进行上传过程还是应该使用 AsyncTask 将数据上传到服务器?
I have to upload data to a server. I am using a service that is running on the same process as my application. Should I use a Separate thread for upload process or Should I use a AsyncTask to upload data to server ?
更具体地说,我可以在服务类中使用 AsyncTask 吗?我应该使用它吗?此服务应始终在内存中运行,以便每 5 秒向服务器发送一次数据.
More specifically can I use AsyncTask inside a service class ? And should I use it ? This service should always be running in memory in order to send data to the server every 5 seconds.
推荐答案
是的,你可以,下面的代码将每 5 秒运行一次.使用您的常规连接代码发送部分.
Yes you can, the below code will run every 5 seconds. Use your regular connection code for sending part.
public class AsyncTaskInServiceService extends Service {
public AsyncTaskInServiceService() {
super("AsyncTaskInServiceService ");
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
protected void onHandleIntent(Intent intent) {
final Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Connect to database here
try {
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 0, 5000);
}
}
这篇关于在服务类中使用 AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在服务类中使用 AsyncTask?


基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01