Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 457
hixhix Avatar asked Sep 26 '22 22:09

hixhix


1 Answers

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/

like image 84
Sree Avatar answered Oct 06 '22 00:10

Sree