How do I pass data between Activities/Services within a sing
How do I pass data between Activities/Services within a single application?转载: http://developer.android.com/resources/faq/framework.htmlIt depends on the type of data that you want to share: Primitive Data TypesTo share primitive data between Activities/Services in an application,use Intent.putExtras(). For passing primitive data that needs to persist use thePreferencesstorage mechanism. Non-Persistent ObjectsFor sharing complex non-persistent user-defined objects for short duration,the following approaches are recommended: Singleton class You can take advantage of the fact that your application components run in the same process through the use of a singleton. This is a class that is designed to have only one instance. It has a static method with a name such as A public static field/methodAn alternate way to make data accessible across Activities/Services is to usepublic staticfields and/or methods. You can access these static fields from any other class in your application. To share an object,the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field. A HashMap of WeakReferences to ObjectsYou can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity,it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retrieves the object using this key. Persistent ObjectsEven while an application appears to continue running,the system may choose to kill its process and restart it later. If you have data that you need to persist from one activity invocation to the next,you need to represent that data as state that gets saved by an activity when it is informed that it might go away. For sharing complex persistent user-defined objects,the following approaches are recommended:
If the shared data needs to be retained across points where the application process can be killed,then place that data in persistent storage like Application Preferences,SQLite DB,Files or ContentProviders. Please refer to theData Storagefor further details on how to use these components. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |