简体   繁体   English

从非活动类获取活动的结果

[英]Getting the result of an activity from a non-activity class

<summary> <摘要>

Is there an elegant way of getting the result of an activity from a non-activity class, or is it always going to be a hack? 是否有一种从非活动类获取活动结果的优雅方法,还是总是会被黑客入侵? Would I be better avoiding that situation if possible? 如果可能的话,我会更好地避免这种情况吗?

</summary> </ summary>

I have an activity, that has an instance of a session for a web service, which will generally be pre-authenticated (the session key will be saved in SharedPreferences). 我有一个活动,其中有一个Web服务会话的实例,通常将对其进行预先认证(会话密钥将保存在SharedPreferences中)。 However, the first time it runs, I will need to pop up a log in activity, which will return the username and password to the session, which will then talk to the server and get a session key. 但是,第一次运行时,我将需要弹出一个登录活动,该活动将用户名和密码返回到会话,然后再与服务器对话并获取会话密钥。

Ideally, I would like to have the non-activity session class call startActivityForResult, but I'm not sure it's possible. 理想情况下,我希望非活动会话类调用startActivityForResult,但是我不确定是否有可能。 I've seen various questions about how it can be done: 我已经看到各种有关如何完成的问题:

How to get the result from OnActivityResult inside another class?(outside of the activity 如何从另一个类内部的OnActivityResult获取结果?(在活动外部)

use startActivityForResult from non-activity 使用非活动中的startActivityForResult

But they all seem a little hacky. 但是他们似乎都有些。 I've also seen this, which suggests that passing round contexts is not the best idea anyway: 我也看到了这一点,这表明传递上下文始终不是最好的主意:

http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html

Another option is to save the username and password to sharedpreferences and retrieve it in the other class, but then I'd have to have some way of figuring out when it had been saved, and it all seems to be getting rather messy. 另一个选择是将用户名和密码保存到sharedpreferences中,然后在另一个类中检索它,但是然后我必须要有某种方法来弄清楚何时保存了它,而且似乎都变得一团糟。

Another option is to make the session a non-displaying activity. 另一种选择是使会话成为非显示活动。 Seems like a large overhead though. 似乎开销很大。

My project is still in planning stages, so I'm after best practice. 我的项目仍处于计划阶段,因此我追求最佳实践。 What is the most elegant way to do this? 最优雅的方法是什么?

我将使用事件总线(例如Otto,GreenRobot)将活动的结果传达给非活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM