Android 如何获取我的活动上下文?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12320857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:25:33  来源:igfitidea点击:

How to get my activity context?

androidandroid-context

提问by Ofek Ron

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

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

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

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

采纳答案by hasanghaforian

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

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

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.

那些需要维护全局应用程序状态的基类。您可以通过在 AndroidManifest.xml 的标记中指定其名称来提供您自己的实现,这将导致在创建应用程序/包的进程时为您实例化该类。

To use this class do:

要使用此类,请执行以下操作:

public class App extends Application {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

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

    ...

}

In your manifest:

在您的清单中:

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

In Activity B:

在活动 B 中:

public class B extends Activity {

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

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

In class A:

在 A 类中:

Context c = App.getContext();

Note:

注意

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.

通常不需要子类化应用程序。在大多数情况下,静态单例可以以更加模块化的方式提供相同的功能。如果您的单例需要全局上下文(例如注册广播接收器),则可以为检索它的函数提供一个 Context,该 Context 在首次构造单例时在内部使用 Context.getApplicationContext()。

回答by Gan

Ok, I will give a small example on how to do what you ask

好的,我将举一个小例子来说明如何做你所要求的

public class ClassB extends Activity
{

 ClassA A1 = new ClassA(this); // for activity context

 ClassA A2 = new ClassA(getApplicationContext());  // for application context. 

}

回答by John Alexander Betts

The best and easy way to get the activity context is putting .thisafter the name of the Activity. For example: If your Activity's name is SecondActivity, its context will be SecondActivity.this

获取活动上下文的最佳且简单的方法是将其放在.this活动名称之后。例如:如果您的活动名称为SecondActivity,则其上下文将为SecondActivity.this

回答by Shark

you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()

您在其构造函数中将上下文传递给类 B,并确保传递 getApplicationContext() 而不是 activityContext()

回答by Helal Khan

You can create a constructor using parameter Context of class A then you can use this context.

您可以使用类 A 的参数 Context 创建一个构造函数,然后您可以使用此上下文。

Context c;

上下文 c;

A(Context context){ this.c=context }

A(上下文上下文){ this.c=上下文}

From B activity you create a object of class A using this constructor and passing getApplicationContext().

从 B 活动中,您使用此构造函数并传递 getApplicationContext() 创建类 A 的对象。

回答by Serg Burlaka

In Kotlin will be :

在 Kotlin 中将是:

activity?.applicationContext?.let {
         it//<- you context
        }

回答by Thomas

If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

如果您需要 B 中 A 的上下文,则需要将其传递给 B,您可以按照其他人的建议将 Activity A 作为参数传递。我没有看到让 A 的许多实例拥有自己的指向 B 的指针的问题,不确定这是否会带来那么多开销。

But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Applicationclass, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Applicationinstead.

但是,如果这是问题所在,则有可能将指向 A 的指针保留为类的一种全局变量Application,正如@hasanghaforian 所建议的那样。事实上,根据您需要上下文的用途,您甚至可以使用 的上下文来Application代替。

I'd suggest reading this articleabout context to better figure it out what context you need.

我建议阅读这篇关于上下文的文章,以更好地弄清楚您需要什么上下文。