机器人:如何使用getApplication和getApplicationContext非活动/服务类 [英] android: how to use getApplication and getApplicationContext from non activity / service class

查看:165
本文介绍了机器人:如何使用getApplication和getApplicationContext非活动/服务类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Android的推广应用类在整个应用程序共享数据。

I'm using extending application class on Android to share my data across the entire app.

我可以从我的所有活动中使用 getApplication()方法。

I can use getApplication() method from all my activities.

然而,也有我创建某些自定义助手类;例如, XMLHelper 不来自任何活动/服务类继承的类。

However, there are certain custom helper classes I created; for example, an XMLHelper class which does not inherit from any activity / service class.

下面的 getApplication()方法不可用。

我如何排序了这一点,什么是最好的设计实践来解决这个?

How do I sort this out and what are the best design practices to solve this?

推荐答案

getApplication()方法位于活动类,这就是为什么你不能从你的助手类访问它。

The getApplication() method is located in the Activity class, that's why you can't access it from your helper class.

如果你真的需要从你的助手来访问你的应用环境,你应该保持一个对活动的情况,以及调用传递给助手。

If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.

这篇关于机器人:如何使用getApplication和getApplicationContext非活动/服务类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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