1

I'm having a IntentService to perform background request to my API. I'm using Otto Bus to communicate with it.

public class MyService extends IntentService {

    private MyAPI mApi;
    private MyBus mBus;

    MyService () {
        super("MyService ");
    }

    @Subscribe
    public void onLoadSearchData(LoadSearchDataEvent event) {
        Log.d("onLoadSearchData "+ Thread.currentThread().getName());
        mApi.loadSomeData();
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        Thread.currentThread().setName(getClass().getCanonicalName());
        Log.d("Thread name " + Thread.currentThread().getName());
        if (mApi==null) mApi = new MyAPI(getApplicationContext());
        if (mBus==null) {
            mBus = MyBus.getInstance();
            mBus.register(this);
        }
    }

}

The onHandleIntent is performed on a secondary thread, which is normal. But when i call onLoadSearchData with a bus event from the main ui, it runs on the UI thread !!!!

I don't understand why.

My purpose is to have a background thread to load/cache data.

Not sure how to do this. Thanks for the help.

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
user1391967
  • 497
  • 1
  • 6
  • 13

1 Answers1

2

I don't understand why.

Quoting the Otto documentation:

By default, all interaction with an instance is confined to the main thread

More specifically, Otto delivers messages on the same thread where they are posted from.

My purpose is to have a background thread to load/cache data.

IntentService has a background thread, but only to invoke onHandleIntent(). Once onHandleIntent() returns, not only does the thread go away, but the service gets destroyed.

I am unclear why you think you need a service here. Assuming that you do, you will need to use a regular service and arrange for your own background thread, so that you can better control the lifetime of the service and the thread.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Ok. IntentService is no good. Let's say i have a service to manage my threads. It runs ont the UI threads so no problem to use Otto to communicate with my activity. But will i be able to use Otto to send back Events from my threads to the UI ? – user1391967 May 29 '15 at 19:04
  • @user1391967: While you can use Otto, you would have to use its `ThreadEnforcer.ANY` setting (see their docs), and the messages would be delivered on the background thread, forcing the activity to use `runOnUiThread()` or something. Personally, I use greenrobot's EventBus, which works like Otto but has more flexible threading options. – CommonsWare May 29 '15 at 19:15
  • Well, i will try a service to run threads and use Greenrobot's evenbus. Thanks. – user1391967 May 29 '15 at 19:24