Android的活动之间的数据共享 [英] Data Sharing Between Android Activities

查看:166
本文介绍了Android的活动之间的数据共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个一直缠着我有一段时间了一个问题。我想知道什么被认为是规范的,或最好的做法,意味着让数据从一个活动到另一个。我个人知道的两种方法可以做到这一点。第一种方式是通过直接捆绑数据到经由putExtra()函数(或类似的东西)的意图。然而,这种方式对我来说似乎有点违反封装原则。我这样做的第二种方式是通过将数据放置到一个单独的类,并共享两个活动之间的类。这似乎是更根本的声音,但我仍然不确定。任何人都关心阐明这一些轻?

I have a question that has been bugging me for a while now. I would like to know what is considered the canonical, or best practice, means of getting data from one activity to another. I am personally aware of two ways to do this. The first way is by bundling the data directly into the Intent via the putExtra() function (or something similar). However, this way seems to me to be a bit of a violation of encapsulation principles. The second way I have done this is by placing the data into a separate class, and sharing that class between the two activities. This seems to be more fundamentally sound, but I am still unsure. Anyone care to shed some light on this?

推荐答案

我wrighting我的应用程序时,有同样的问题,我结束了创建一个扩展应用类我CustomApplication类并将其添加到我的Andr​​oidManifest标签。 XML。这样我可以存储任何类型的数据里面有适当的getter和setter。调用(CustomApplication).getApplicationContext()将返回CustomApplication对象,这是为您的整个应用程序的唯一和存在于单一实例(单身),并使用您可以设置和获取necessery值。

I've had the same question when wrighting my app and I ended up creating my CustomApplication class that extends Application class and adding it to the tag in my AndroidManifest.xml. This way I can store any types of data inside it with proper getters and setters. Calling (CustomApplication).getApplicationContext() will return CustomApplication object, which is unique for your whole app and exists in single instance(singleton) and using which you can set and get necessery values.

这样做的好处是,它在你的应用程序对象和数据,只要存在为您的应用程序(活动,服务等)的任何部分正在运行。

The benefit is that your Application object and data within it exists as long as any part of your app(Activities, Services, etc) is running.

这篇关于Android的活动之间的数据共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆