Android的活动之间的数据共享

编程入门 行业动态 更新时间:2024-10-25 18:31:26
本文介绍了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的活动之间的数据共享

本文发布于:2023-08-01 12:26:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268312.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!