如何获取我的活动上下文? [英] How to get my activity context?

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

问题描述

我真的不明白这整个事情是如何工作的真正背后的想法,所以如果我有一些类 A 需要一个类 B 的上下文,它扩展Activity,我如何获得那个上下文?

I don't really get the idea behind how this whole thing works really, so if I have some class A that need the context of a class B which extends Activity, how do i get that context?

我正在寻找一种比将上下文作为参数提供给 A 类构造函数更有效的方法.例如,如果 A 类将有数百万个实例,那么我们最终将拥有数百万个指向 Context 的冗余指针,而我们应该能够以某种方式在某处只有一个一个 getter 函数...

I'm searching for a more efficient way than giving the context as a parameter to class A constructor. For example if class A is going to have millions of instances then we would end up having millions of redundant pointer to Context while we should be able somehow to have just one somewhere and a getter function...

推荐答案

可以使用Application类(android.application包中的公共类),即:

You can use Application class(public class in android.application package),that is:

需要维护全局应用程序状态的基类.您可以通过在您的AndroidManifest.xml 的标签,这将导致该类当您的进程为您实例化时应用程序/包已创建.

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

要使用这个类:

public class App extends Application {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    public static void setContext(Context mContext) {
        this.mContext = mContext;
    }

    ...

}

在您的清单中:

<application
        android:icon="..."
        android:label="..."
        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

在活动 B 中:

public class B extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampleactivitylayout);

        App.setContext(this);
                  ...
        }
...
}

在A类:

Context c = App.getContext();

注意:

通常不需要子类化应用程序.大多数情况下,静态单例可以以更模块化的方式提供相同的功能道路.如果您的单身人士需要全局上下文(例如注册广播接收器),可以给出检索它的函数Context 内部使用 Context.getApplicationContext() 时首先构造单例.

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

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

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