Robospice - keep spice service continue running when changing activity

荒凉一梦 提交于 2019-12-03 14:21:37

@R4j, you missed the point. Requests are not stopped when the activity holding the spicemanager stops. In RS, requests will have their own lifecycle and will be exectued in a different context (a spice service that is an Android Service).

Thus, if you fire a request, then your activity dies or gets killed, the spice request will go on its own way and download will continue. Parsing will occur as well, and finally your result will be placed in the cache. If any.

So if you want to trigger a request in activity A and get the result in activity B, you should :

  • simply execute the request in activity A as usual, follow RS samples
  • in B, after starting your spiceManager (i.e. right after super.onStart()), do 2 things :

    • use spiceManager.addListenerIfPending to replug the new activity on any pending request
    • use spiceManager.getDataFromCache to get any result that could already have been put in the cache by a previous request
  • optionnally, if you want to re-execute the request in B itself, you can, and you will be happy to learn that if you use the same request class with the same cache key, RS will aggregate your new request to any pending request for you.

In RS, a request is identified by a compound key made of "class of result of a request" + "request cache". This compound key can be used to retrieve a pending request as well as any result put by this request in the cache.

Declate a spicemanager instance in your application class and access it in activity to start background service.

public class MyApplication extends Application {

    private static MyApplication instance;
        private SpiceManager spiceManager = new SpiceManager(RequestService.class);

    @Override
    public void onCreate() {
        super.onCreate();
    }


    public SpiceManager getManager()
    {
       return spiceManager;
    }

}

In Activity, you can call it. See my code below.

((MyApplication) getApplicationContext()).getSpiceManager().startService(........);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!