Answer the question
In order to leave comments, you need to log in
What is the most efficient way to pass an object from an IntentService to an Activity?
Implementing a Web client on Android. Http requests are made in IntentService
. As a result, the service generates objects that have not only primitive types, but also, for example, Bitmap
. What is the best way to pass an object to an Activity, or some intermediate class.
The simplest use case ResultReceiver
, as I understand it, does not work.
In a callback method
void onReceiveResult(int resultCode, Bundle resultData)
comes a Bundle object, which is only suitable for storing simple types. Translating Bitmap
- object to byte array is not recommended. Parcel
and shove it into Intent
. Then catch with BroadcastReceiver
. Is it recommended to send weighty objects? OutputStream
and pass the path? Or just save as a static variable somewhere? I'm not an expert on the weaknesses of Android, I want the main thing is that the application remains nimble. Thanks in advance for your replies!
Answer the question
In order to leave comments, you need to log in
In general, probably already a classic - this is EventBus.
However, if you do not want to include extra libraries, then I recommend that you look towards AsyncLoader instead of a service. After all, you don't need the request to go if the application is killed. But in return, you will get a convenient receipt of the results of an asynchronous request.
Data from a service must always be passed through a Bundle.
Because: as soon as you want to separate the service from the main application, android:process=":remote"
then all the simplifications (passing through a static variable, EventBus, etc.) will simply stop working (due to different Application instances).
As for the Bitmap - you wrote everything correctly - they need to be saved to disk and passed the URI.
Because: this situation often happens: the
Service loaded the picture -> gave it to the Activity by reference to the object -> after which the service completed its work and was destroyed along with its Context -> accordingly, the picture created in the context of the Service was also cleared. Now the Activity has a reference to the cleared Bitmap -> as a consequence
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question