executing asynchronous task from service in androi

2019-08-02 14:34发布

问题:

I was developping an application and I ran into a problem. I was trying to run an asynchronous task from a service and it didn't work. It says that the code is unreachable. Now I knwo that both run in Background, but I really want one service to control several asyncronous tasks. how can I do that? Do I have to use threads? I've read this post and I really want to use the asyncronous task: Difference between Service, Async Task & Thread?

Also, is it possible to execute an asynchronous task from another one?

Thank you

回答1:

AsyncTask always works on main/UI thread. And if your Service is running under a different process then it is not associated to main thread, that's why you cant use AsyncTask in Service.

In your case, you are encouraged to use HandlerThread, Looper and Handler to perform heavy lifting on separate thread.

Read this article.



回答2:

you can use HandlerThread in your service for doing background work like:

public class ServicewithHandlerThread extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {

          while (true) {
              synchronized (this) {
                  try {
                      //YOUR BACKGROUND WORK HERE
                  } catch (Exception e) {
                  }
              }
          }
          stopSelf(msg.arg1);
      }
  }
  @Override
  public void onCreate() {
    // Start up the thread running the service.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);
      return START_STICKY;
  }
  @Override
  public IBinder onBind(Intent intent) {
      return null;
  }
}


回答3:

There's a few options. If you need communication between your task and say, an activity, AsyncTask would be your best best, IMO. If you just need to "fire and forget", IntentService can be of help.

Remember, a service still runs on the main thread. If you need to do anything that requires some processing or lookup such as network download/upload or SQL queries, you should move that to a new thread using on of the aforementioned classes.