在服务类中使用 AsyncTask? [英] Using an AsyncTask inside a Service Class?

查看:30
本文介绍了在服务类中使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆