Skip to content Skip to sidebar Skip to footer

Is It Possible To Use Asynctask In A Service Class?

Everything is in the title. On the official documentations it is stated that Note that services, like other application objects, run in the main thread of their hosting process and

Solution 1:

Also be sure to check out IntentService. If that class is sufficient for your needs, it will take care of a lot of little details involved in making that pattern work correctly.

Solution 2:

I Think I found why it is not working in my case.

Here I am using this :

privatefinal INetwork.StubmBinder=newINetwork.Stub() {

        @OverridepublicintdoConnect(String addr, int port)throws RemoteException {
            newConnectTask().execute("test42");
            return0;
        }
    };

I am using this to do what so called IPC, Inter Process Communication, so I guess that my Service and my Activity are in two differents process, AsyncTask must be executed in the main UI thread according to the android doc, so why I was trying to do seems to me just impossible according to those facts.

If I am wrong please someone can correct me.

Solution 3:

Maybe problem is not AsyncTask but something else. For example are you sure your onBind method works correctly? Please try this:

@Overridepublic IBinder onBind(Intent arg0) {
    returnnull;
}

You could also try that

publicclassNetworkServiceextendsService{
  @OverridepublicvoidonStart(Intent intent, int startId) {
    newConnectTask().execute("test42");
  }
}

Solution 4:

Is it possible to use AsyncTask in a Service class?

Yes. See Reto Meier (2010) Professional Android 2 Application Development, Wrox. Meier has published supporting code (see /Chapter 9 Earthquake 4/src/com/paad/earthquake/EarthquakeService.java):

publicclassEarthquakeServiceextendsService {        
    ... 
    privateEarthquakeLookupTasklastLookup=null;
    ...

    privateclassEarthquakeLookupTaskextendsAsyncTask<Void, Quake, Void> { 
        ... 
    }

    @OverridepublicintonStartCommand(Intent intent, int flags, int startId) {    
        ...
        refreshEarthquakes();
        return Service.START_NOT_STICKY;
    };

    privatevoidrefreshEarthquakes() {
        ...
        lastLookup = newEarthquakeLookupTask();
        lastLookup.execute((Void[])null);
        ...
    }
}

On an aside, I cannot find any evidence to support your claim that "AsyncTask only works if it is executed in the UIThread" (although this would violate threading rules).

Solution 5:

Although it is possible to use AsyncTask in a Service class, this violates threading rules, in particular, AsyncTask must be instantiated and invoked on the UI thread. (See https://stackoverflow.com/a/25172977/3664487 for further discussion.)

Post a Comment for "Is It Possible To Use Asynctask In A Service Class?"