在Android的活动之间传递的非基本类型的数据类型、基本、数据、Android

2023-09-11 12:43:27 作者:初遇

假设你想开始一个新的活动,并从当前的活动传递一些数据。如果数据是基本类型,你可以简单地使用的意图,并添加额外的,但你会怎么做到这一点的更复杂的数据结构,如的ArrayList或对象?

Suppose you want to start a new activity and pass it some data from the current activity. If the data is of a primitive type you could simply use an intent and add extras, but how would you do this for more complex data structures like arraylists or objects?

推荐答案

您有几种选择:

您可以在实现 Parcelable 接口,这可以被存储在一个额外的一类包住更复杂的结构 您可以在一类用于实现序列化接口,这可以被存储在一个额外的包住更复杂的结构 您使用静态数据成员传递的东西左右,因为它们都是在同一个进程 您使用外部存储(文件,数据库,共享preferences ) 作为一个谁刚刚张贴的人指出,使用共同的组件,如自定义应用程序或本地服务 You could wrap the more complex structure in a class that implements the Parcelable interface, which can be stored in an extra You could wrap the more complex structure in a class that implements the Serializable interface, which can be stored in an extra You use static data members to pass stuff around, since they are all in the same process You use external storage (file, database, SharedPreferences) As the person who just posted noted, use a common component, such as a custom Application or a local Service

你不想做的就是通过额外的传球大的东西。例如,如果你正在创建抓住的照片从相机的应用程序,你不想把它们放到群众演员 - 使用静态数据成员(如恶心听起来)。意图的设计工作,跨进程,这意味着有数据拷贝的一定量的推移,要避免时,没有必要为大的东西。

What you do not want to do is pass big stuff via extras. For example, if you are creating an application that grabs pictures off the camera, you do not want to pass those in extras -- use a static data member (icky as that sounds). Intents are designed to work cross-process, which means there is some amount of data copying that goes on, which you want to avoid when it is not necessary for big stuff.