Java 在服务类中使用 AsyncTask?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22043652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:14:38  来源:igfitidea点击:

Using an AsyncTask inside a Service Class?

javaandroidandroid-asynctaskandroid-service

提问by Rakesh

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 将数据上传到服务器?

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.

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

采纳答案by user666

Yes you can, the below code will run every 5 seconds. Use your regular connection code for sending part.

是的,你可以,下面的代码将每 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);
    }
}

回答by Pierre Rust

No problem to use AsyncTask in a service.

在服务中使用 AsyncTask 没问题。

NOTE / FIX :I was wrong when I said the service runs in background, it only applis to IntentService. As noted in the comments and in the documentation, a service does not create it's own thread :

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

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.

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

That means you mustuse an AsyncTask (or another thread in any case) to perform your upload task.

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

回答by Shriyanshu Jain

Use AsyncTask in a service in android

在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();

????????} ?

???}

} 

Try this it may be work. Thank you.

试试这个它可能是工作。谢谢你。