Data transmission
During Android development, we often pass data between components through Intent. For example, in usingstartActivity()
When a method starts a new activity, we can create itIntent
The object is then calledputExtra()
Method transfer parameters.
val intent = Intent(this, TestActivity::) ("name","name") startActivity(intent)
After starting the new Activity, we can get the transmitted data in the new Activity.
val name = getIntent().getStringExtra("name")
Generally speaking, the data we pass is very small, but sometimes when we want to transmit a large object, such as a bitmap, there may be problems.
val intent = Intent(this, TestActivity::) val data= ByteArray( 1024 * 1024) ("param",data) startActivity(intent)
An exception will be thrown when the method is called to start a new activity.
: data parcel size 1048920 bytes
Obviously, the reason for the error is that the amount of data we transmit is too large. There is a description in the official documentation:
The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size。
That is, the buffer is up to 1MB, and this is common to all the in-progress transport objects in the process. So the data size we can transmit should actually be smaller than 1M.
Alternatives
- We can share data through static variables
- use
()
Method to complete the big data transmission.
Since we want to store the data in Binder, we first create a class inherited from Binder. data is the data object we pass.
class BigBinder(val data:ByteArray):Binder()
Then pass
val intent = Intent(this, TestActivity::) val data= ByteArray( 1024 * 1024) val bundle = Bundle() val bigData = BigBinder(data) ("bigData",bigData) ("bundle",bundle) startActivity(intent)
Then start the new interface normally and find that it can jump over, and the new interface can also receive the data we pass.
Why can the 1M buffer limit be bypassed in this way? This is because when passing directly through Intent, the system adopts the copy to the buffer, while the putBinder method uses shared memory, and the shared memory limit is much larger than 1M, so there will be no exceptions.
This is the end of this article about Android using Intent to pass component big data. For more related Android Intent content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!