简体   繁体   中英

Retrofit when activity is destroyed

I see different examples regarding retrofit (Performing restapi from android) where they write the code/put the callback in the activity as in the following link: I was wondering whether this is a correct approach ? I read that problems could be triggered if the activity is destroyed due to a phone call for example. If this is correct, I would appreciate an explanation why the destruction of the activity does not influence application ?

Thanks, Clint

Why the destruction of the activity does not influence application ?

As you may know Android does not allow network interaction on main thread. It throws a NetworkOnMainThreadException . It is suggested to do all the network processing either in background or in worker threads. Retrofit library is powerful enough to support this. Retrofit make asynchronous background requests.

I would separate all http calls from Activity/Fragment to Background Service which is not affected by screen rotation and other runtime changes.

So you can move the Retrofit job to Service, and after receiving data you can pass them back again to your Activity/Fragment using Event Bus.

You can use one of the following library to do that

  1. EventBus
  2. Otto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM