在服务类中使用AsyncTask?

时间:2014-02-26 14:00:28

标签: java android android-asynctask android-service

我必须将数据上传到服务器。我正在使用与我的应用程序在同一进程上运行的服务。我应该使用单独的线程进行上传过程还是应该使用AsyncTask将数据上传到服务器?

更具体地说,我可以在服务类中使用AsyncTask吗?我应该使用它吗?此服务应始终在内存中运行,以便每5秒向服务器发送一次数据。

3 个答案:

答案 0 :(得分:5)

在服务中使用AsyncTask没问题。

注意/ FIX:当我说服务在后台运行时,我错了,它只适用于IntentService。正如评论和documentation中所述,服务不会创建自己的线程:

  

警告:服务在其托管进程的主线程中运行 - 该服务不会创建自己的线程,也不会在单独的进程中运行(除非您另行指定)。这意味着,如果您的服务要进行任何CPU密集型工作或阻止操作(例如MP3播放或网络),您应该在服务中创建一个新线程来完成这项工作。

这意味着您必须使用AsyncTask(或任何情况下的其他线程)来执行上传任务。

答案 1 :(得分:2)

是的,您可以,以下代码将每5秒运行一次。使用常规连接代码发送部件。

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);
    }
}

答案 2 :(得分:-5)

在Android

中的服务中使用AsyncTask
package ​com.emergingandroidtech.Services;

import ​android.app.Service;

import​ android.content.Intent;

import​ android.os.IBinder;

import ​android.util.Log;

import​ android.widget.Toast;

import​ java.net.MalformedURLException;

import​ java.net.URL;

import android.os.AsyncTask;

public​ class ​MyService ​extends​ Service​

{

​​​​@Override

​​​​public​ IBinder ​onBind(Intent​ arg0)​

{

​​​​​​​​return ​null;

​​​​}

​​​​

@Override ​

​​​public​ int ​onStartCommand(Intent ​intent,​int​ flags,​int ​startId)​

{

​​​​​​​​

//​We​ want ​this ​service ​to ​continue ​running ​until​ it ​is ​explicitly

​​​​​​​​//​stopped,​so​ return ​sticky. ​​​​​​​​

Toast.makeText(this,​“Service​Started”,​Toast.LENGTH_LONG).show();

​​​​​​​​try

{

​​​​​​​​​​​​new DoBackgroundTask().execute(

​​​​​​​​​​​​​​​new URL(“http://www.google.com/somefiles.pdf”),

​​​​​​​​​​​​​​​​​​​​new URL(“http://emergingandroidtech.blogspot.in”)); ​​​​​​​​

}

catch (MalformedURLException e)

{

​​​​​​​​​​​​e.printStackTrace();

​​​​​​​​}

​​​​​​​​return ​START_STICKY; ​

​​​}

​​​​

@Override

​​​​public ​void ​onDestroy()

​{

​​​​​​​​super.onDestroy();

​​​​​​​​Toast.makeText(this,​“Service​Destroyed”,​Toast.LENGTH_LONG).show(); ​​​

​} ​​​​

​​​​private ​int ​DownloadFile(URL​ url)

​{

​try​

{

​​​​​​​​​​​​//---simulate​ taking ​some​time ​to ​download ​a​ file--- ​​​​​​​​​​​​

Thread.sleep(5000);

​​​​​​​​}

​catch​(InterruptedException ​e)​

{

​​​​​​​​​​​​e.printStackTrace(); ​

​​​​​​​}

​​​​​​​​//---return ​an ​arbitrary ​number​ representing ​

​​​​​​//​the ​size​ of ​the ​file ​downloaded--- ​

​​​​​​​return​ 100; ​

​​​}

​​​​

private class DoBackgroundTask extends AsyncTask<URL, Integer, Long>

{

​​​​​​​​protected Long doInBackground(URL... urls)

{

 ​​​​​​​​​​​​int count = urls.length;

​​​​​​​​​​​​long totalBytesDownloaded = 0;

​​​​​​​​​​​​for (int i = 0; i < count; i++)

{

​​​​​​​​​​​​​​​​totalBytesDownloaded += DownloadFile(urls[i]);

​​​​​​​​​​​​​​​​//---calculate percentage downloaded and

​​​​​​​​​​​​​​​​// report its progress--- ​

​​​​​​​​​​​​​​​publishProgress((int) (((i+1) / (float) count) * 100)); ​

​​​​​​​​​​​}

​​​​​​​​​​​​return totalBytesDownloaded; ​​

​​​​​​}

​​​​​​​​

protected void onProgressUpdate(Integer... progress)

{

​​​​​​​​​​​​Log.d(“Downloading files”, ​​​​​​​​​​​​​​​​​​​​String.valueOf(progress[0]) + “% downloaded”); ​​​​​​​​​​​​

Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​String.valueOf(progress[0]) + “% downloaded”, ​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​​​​​​​

}

​​​​​​​​

protected void onPostExecute(Long result)

{

​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“Downloaded “ + result + “ bytes”, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​

​​​​​​​​​​stopSelf();

​​​​​​​​} ​

​​​}

} 

试试这可能有用。 谢谢。