D
D
dimonkoz2016-05-12 14:29:03
Android
dimonkoz, 2016-05-12 14:29:03

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.
The second option is to pack the object into Parceland shove it into Intent. Then catch with BroadcastReceiver. Is it recommended to send weighty objects?
Perhaps you can just save the image through OutputStreamand 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

2 answer(s)
M
MaxF, 2016-05-12
@MaxF

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.

L
lazard105, 2016-05-13
@lazard105

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

PS if the application is simple and you want to use simple methods of interacting with the service, then write a separate manager that will be responsible for transferring data (then it's easier to redo it with Bundle ;) )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question