机器人:如何使用getApplication和getApplicationContext非活动/服务类如何使用、机器人、getApplicationContext、getApplication

2023-09-03 21:15:56 作者:③岁就很帥

我使用的是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.