hixhix
hixhix

Reputation: 791

are contexts of Android Activity/Application/Service the same object if they belong to the same app?

Is it safe to assume that getApplicationContext in Application and getContext in AbstractThreadedSyncAdapter return the same object? How about other case where we get context from activity, service.... all belong to the same app. Thanks.

Upvotes: 5

Views: 725

Answers (1)

Sree
Sree

Reputation: 2787

No they are not. Here is the jist:

Application – is a singleton instance running in your application process. It can be accessed via methods like getApplication() from an Activity or Service, and getApplicationContext() from any other object that inherits from Context. Regardless of where or how it is accessed, you will always receive the same instance from within your process.

Activity/Service – inherit from ContextWrapper which implements the same API, but proxies all of its method calls to a hidden internal Context instance, also known as its base context. Whenever the framework creates a new Activity or Service instance, it also creates a new ContextImpl instance to do all of the heavy lifting that either component will wrap. Each Activity or Service, and their corresponding base context, are unique per-instance.

This article really helps clear it out: https://possiblemobile.com/2013/06/context/

Upvotes: 4

Related Questions