在 Android 库中获取上下文 [英] Get Context in Android library

查看:68
本文介绍了在 Android 库中获取上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Android 应用程序,它的一些功能封装在一个内部库中.但是,要使此功能起作用,库需要应用程序上下文的实例.为图书馆提供此上下文的最佳方法是什么?我看到了一些选项,但都没有吸引力:

I'm writing an Android app that has some functionality encapsulated in an internal library. However, for this functionality to work, the library needs an instance of the Application Context. What's the best way to give the library this Context? I see a few options, none of them appealing:

  • 让我的库类扩展 Application,并调用 getApplicationContext()
    • 通常不鼓励这样做
    • 这要求每个调用者在使用库之前检索应用程序上下文,并且还要求调用者针对库的实例而不是针对库类上定义的静态方法进行调用(因此还需要保留对此实例的引用).
    • This requires every caller to retrieve the Application Context before using the library, and also requires that the caller call against an instance of the library instead of against static methods defined on the library class (and thus further requires keeping a reference to this instance).

    推荐答案

    为图书馆提供此上下文的最佳方式是什么?

    What's the best way to give the library this Context?

    Context 传递到您的库公开的需要 Context 的方法中.这就是 Android SDK 在某些地方所做的.

    Pass a Context into the methods exposed by your library that need a Context. This is what the Android SDK does in places.

    或者,更改您的库以公开对象,而不是静态方法,并让对象持有 Context 的实例(提供给创建该实例的构造函数或工厂方法).

    Or, change your library to expose objects, not static methods, and have the objects hold an instance of Context (supplied to the constructor or factory method that created the instance).

    让我的库类扩展应用程序,并调用 getApplicationContext()

    Have my library classes extend Application, and call getApplicationContext()

    如果您可以在 Context 上调用 getApplicationContext(),您就可以这样做,而无需对 Application 进行子类化.

    If you can call getApplicationContext() on a Context, you would just do that, without needing to subclass Application.

    这篇关于在 Android 库中获取上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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