Android-在没有onActivityResult()的情况下从活动传回信息的最佳实践是什么? [英] Android - What is the best practice for passing back information from an activity without onActivityResult()?

查看:64
本文介绍了Android-在没有onActivityResult()的情况下从活动传回信息的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个比较笼统的问题. 假设我有一个 MainActivity 形式的 RecyclerView .此RecyclerView的内容正在其他活动的多个位置更新.

I have a rather general question. Assuming I have a RecyclerView in some kind of a MainActivity. The content of this RecyclerView is being updated in multiple places in other activities.

例如,可以通过启动一个新的Activity并将其保存在那里来进行新输入.在这种情况下,我可以直观地以startActivityForResult()启动该活动,并在MainActivity中的onActivityResult()方法中接收更改.

For example there could be the possibility to make new entries by starting a new Activity and saving it there.In that case I would intuitively start that activity with startActivityForResult() and receive the changes in the onActivityResult() method in the MainActivity.

但是可以说,在应用程序内部,可以删除所有条目.现在,我们如何通知MainActivity有关数据集中的更改?我考虑过设置某种标志,然后在MainActivity中更新内容后将其清除.但是以某种方式使用全局变量并不能真正遵循正确封装的原理,对吗?

But lets say deeper inside the application, there is the possibility to delete all entries. Now how do we notify the MainActivity about this change in the dataset? I thought about setting a flag of some kind and clearing it after the content has been updated in the MainActivity. But somehow using global variables does not really follow the principle of proper encapsulation, does it?

很抱歉这个模糊的问题,但是我发现很难以一种优雅的方式正确处理Android中的信息流,所以就在这里.

Sorry for this vague question, but I find it quite hard to properly handle information flow in Android in a elegant manner, so here we are.

推荐答案

文档中找到广播的想法.您需要本地广播,如果只想在您的应用程序中传递数据,则是首选方法.

How about a local broadcast? You can find the idea of broadcast in this document. You need local broadcast and it is preferred if you want to pass data within your app only.

Android应用程序可以从Android系统和其他Android应用程序发送或接收广播消息,类似于发布-订阅设计模式.当感兴趣的事件发生时,将发送这些广播.例如,Android系统会在发生各种系统事件(例如系统启动或设备开始充电)时发送广播.应用程序还可以发送自定义广播,例如,以向其他应用程序通知他们可能感兴趣的内容(例如,已下载一些新数据).

Android apps can send or receive broadcast messages from the Android system and other Android apps, similar to the publish-subscribe design pattern. These broadcasts are sent when an event of interest occurs. For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging. Apps can also send custom broadcasts, for example, to notify other apps of something that they might be interested in (for example, some new data has been downloaded).

这篇关于Android-在没有onActivityResult()的情况下从活动传回信息的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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