1

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

Community
  • 1
  • 1
G Nag
  • 13
  • 1
  • 3

3 Answers3

2

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.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • Handlers are an awesome way to use threads in android, and its also very easy to do so. Regarding your method to work, i cant say anything yet as i haven't seen your code – waqaslam Mar 31 '12 at 18:26
  • i'm afraid yes... ;) but dont worry, we are always here to help you :) – waqaslam Mar 31 '12 at 18:29
  • well it didn't work out. It turned out that I cannot call that static method (that's why i removed my comment, i felt so stupid for forgetting a fundamental rule) – G Nag Mar 31 '12 at 18:29
  • oh thals for the link. I'll try the Handler idea – G Nag Mar 31 '12 at 18:33
  • you are welcome, and feel free to ask questions if you get stuck :) – waqaslam Mar 31 '12 at 18:35
  • ok for the other question, is it possible to execute an asynchronous task from another one? It should be NO, but I want to confirm it – G Nag Mar 31 '12 at 18:38
  • what do you mean "from another one"? – waqaslam Mar 31 '12 at 18:39
  • another asyncronous task... in other words, n activity calls the first asyncronous task which calls the second asyncronous task as it runs. – G Nag Mar 31 '12 at 19:39
  • @JacksOnF1re **Threading rules** available at http://developer.android.com/reference/android/os/AsyncTask.html – waqaslam Nov 03 '15 at 14:33
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;
  }
}
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • 3
    Thanks for the code imrankhan. But I'm getting some error for "Process.THREAD_PRIORITY_BACKGROUND" it says that "THREAD_PRIORITY_BACKGROUND cannot be resolved or is not a field" – G Nag Mar 31 '12 at 18:36
  • 1
    ok just use HandlerThread thread = new HandlerThread("ServiceStartArguments") and see this doc [HandlerThread](http://developer.android.com/reference/android/os/HandlerThread.html) – ρяσѕρєя K Mar 31 '12 at 18:42
  • Gnag, Waqas saying right, AsyncTask always works from UI.In service you can use a thread and use a handler to communicate with it. – ρяσѕρєя K Mar 31 '12 at 18:45
  • Thanks guys, I really appreciate it. I have't had time to try it though. I'll try it tomorrow ang get to you. Many Thanks again – G Nag Mar 31 '12 at 19:38
  • 21
    Had an issues with "THREAD_PRIORITY_BACKGROUND cannot be resolved or is not a field". Solution: import android.os.Process; NOT java.lang.process. – Shadoath Jan 06 '14 at 23:16
0

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.

Phix
  • 9,364
  • 4
  • 35
  • 62