How do a share a large object within an activity in Android?

I have a Network Client class that is receiving a large binary block and parsing it into a usable Java object. The Network Client is on a separate thread from the app’s View. What is the best way to make this object available to the View? I’ve come up with the following solutions, but I feel like none of them are the correct one:

  1. Create the object in the Network Client and let the View access it directly
    • I would send a small message in a Handler telling the View that the data has been updated
    • Con: requires that I synchronize the object between the threads to ensure that the Network Client doesn’t replace the object while the View is accessing it
  2. Serialize (Parcel?) the object in the Network Client and send it through a Handler to the View
    • Pro: there are no questions of ownership of the data
    • Con: would probably be a huge performance drain on the app
  3. Create a reference to the object and pass that to the View
    • I come from a C++ background, and I’m not sure if this is even possible in Java. I C++, I could just send the View a pointer to the object and let it take care of it. That seems like something Java wouldn’t let me do. Is this feasible?

Are any of these solutions advisable, or should I approach the problem in a completely different way?

Answer

If you don’t want to keep downloading when the activity is in the background, then use non-blocking IO, not threads.

If you do want to keep downloading when the activity is in the background, you probably want to use a service. You can make the object Parcelable or so; I think the underlying service implementation passes pointers around if your activity and service are within the same process (I think they are by default, but ICBW).

Leave a Reply

Your email address will not be published. Required fields are marked *