1

Why does Android use parcels to pass data between components (e.g. two Activities)? Why not just a reference to the object?

Daiwik Daarun
  • 3,804
  • 7
  • 33
  • 60

2 Answers2

1

Parcel is a container for a message(data and object references). In transmission, Parcel contains a byte stream version of a chosen Java Object that contains information about it's attributes. Such data is written to Parcel at sending component, and is read at receiving component. Because the protocol is also designed to support IPC(Inter-Process Communication), only a reference wouldn't suffice. If you really want to use just a reference you can declare your object containing data public static, although I wouldn't recommend this because of the global scope & tight coupling of components.

Trent Oh
  • 179
  • 2
  • 6
  • 1
    `Because the protocol is also designed to support IPC(Inter-Process Communication), only a reference wouldn't suffice.` yep this is why, Activities can belong to a different app than your own. – EpicPandaForce Jun 19 '17 at 16:42
0

If we look at common ways of sharing data between activities, we can make a reasonable guess at why this is the case.

Alternatives include using singletons and SharedPreferences - entities that basically act as "owners" of the state stored by the data. The use of a third party keeps the activities decoupled, as compared to activities simply giving each other references.

We want activities to be decoupled since any two activities should be fairly distinct entities, with possibly independent lifecycles. This is why if we can simply pass information by value (rather than keep a live reference dependency), we should. This is also why it's comparable to Inter-Process Communication, which works around the lack of shared memory.

J. Song
  • 85
  • 6