关于这两种情况是什么,已经有很多帖子了。但我还是不太明白
就我目前的理解而言:
每个都是其类的一个实例,这意味着一些程序员建议您尽可能经常使用this.getApplicationContext(),以免“泄漏”出任何内存。这是因为另一个This(获取Activity实例上下文)指向一个Activity,每当用户倾斜手机或离开应用程序时,Activity就会被销毁。显然垃圾收集器(GC)没有捕获,因此使用太多的内存..
但是谁能想出一些真正好的编码示例,在这些示例中使用this(获取当前Activity实例的上下文)是正确的,而应用程序上下文将是无用的/错误的?
我想知道为什么不使用应用程序上下文的每一个操作,它支持。最后,它降低了内存泄漏和getContext()或getActivity()缺失空检查的可能性(当使用注入的应用程序上下文或通过静态方法从application获得时)。像哈克伯恩女士所说的只在需要的时候使用应用程序上下文这样的陈述,如果没有解释原因,对我来说似乎没有说服力。但我似乎找到了一个不明确的原因:
have found that there are issues on some Android version / device combinations that do not follow these rules. For instance, if I have a BroadcastReceiver that is passed a Context and I convert that Context to an Application Context and then try to call registerReceiver() on the Application Context there are many instances where this works fine, but also many instances where I get a crash because of a ReceiverCallNotAllowedException. These crashes occur on a wide range of Android versions from API 15 up to 22.
https://possiblemobile.com/2013/06/context/#comment-2443283153
因为不能保证下表中应用程序上下文所支持的所有操作都能在所有Android设备上运行!
使用哪个上下文?
有两种类型的上下文:
Application context is associated with the application and will always be same throughout the life of application -- it does not change. So if you are using Toast, you can use application context or even activity context (both) because toast can be displayed from anywhere with in your application and is not attached to a specific window. But there are many exceptions, one exception is when you need to use or pass the activity context.
Activity context is associated with to the activity and can be destroyed if the activity is destroyed -- there may be multiple activities (more than likely) with a single application. And sometimes you absolutely need the activity context handle. For example, should you launch a new activity, you need to use activity context in its Intent so that the new launching activity is connected to the current activity in terms of activity stack. However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.
让我们考虑一些情况:
MainActivity。这是指MainActivity上下文,它扩展了Activity类,但是基类(Activity)也扩展了context类,所以它可以用来提供活动上下文。
getBaseContext()提供活动上下文。
getApplication()提供应用程序上下文。
getApplicationContext()也提供了应用程序上下文。
欲了解更多信息,请点击此链接。