简体   繁体   中英

How should I make my service accessible to other activities in my Android app?

I just started learning Java/Android development and have used Retrofit to create a service that retrieves data from an API. I create this service in my MainActivity, but I want other activities to use this service. For example, if the MainActivity is a search that calls service.search(query) and displays the results, I would want to pass that service to an InfoActivity when the user selects a result so that it can make API calls itself and so on.

However, I'm confused as to how I should do this. Intents seem mainly suitable for primitive objects, I can't seem to serialize Retrofit services either (java.io.NotSerializableException: retrofit2.Retrofit) to put it into an intent. I'm not sure if making the service global is the right thing to do either because I've read that Android will sometimes reset them without warning.

Could someone point me into the right direction of how I should do this?

<service android:name=".MyService" android:exported="true"/>

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