简体   繁体   English

如何区分ApplicationContext和Context?

[英]How to differentiate between ApplicationContext and Context?

I have a Android method which receives instance of Context object, I want to differentiate if the passed context object is returned using one of the following methods 我有一个接收Context对象实例的Android方法,我想区分是否使用以下方法之一返回传递的上下文对象

  • View.getContext() : Returns the context the view is currently running in. Usually the currently active Activity. View.getContext() :返回视图当前正在其中运行的上下文。通常是当前活动的Activity。

  • Activity.getApplicationContext() : Returns the context for the entire application (the process all the Activities are running inside of). Activity.getApplicationContext() :返回整个应用程序的上下文(所有Activity在其中运行的进程)。 Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity. 如果您需要一个与整个应用程序的生命周期相关联的上下文,而不仅仅是当前的Activity,请使用它代替当前的Activity上下文。

Since both methods return instance of Context object but with different capabilities, how can I differentiate if passed context object is Activity Context or Application Context ? 由于这两种方法都返回Context对象的实例,但功能不同,因此如何区分传递的上下文对象是Activity Context还是Application Context?

Since both methods return instance of Context object but with different capabilities, how can I differentiate if passed context object is Activity Context or Application Context ? 由于这两种方法都返回Context对象的实例,但功能不同,因此如何区分传递的上下文对象是Activity Context还是Application Context?

you can check with instanceof . 您可以使用instanceof检查。 It allows to check if the object is of a certain type. 它允许检查对象是否为某种类型。 Eg 例如

 if (context instanceof Activity) {

 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM