Difference between Activitycontext and Applicationcontext

Asked

Viewed 31 times

1

What’s the difference between ActivityContext and ApplicationContext?

The following code, executed from a Fragment, log the message "are different":

 if (getActivity().getApplicationContext().equals(getContext())) {
     Log.d("Context", "São iguais");
 } else {
     Log.d("Context", "São diferentes");
 }

The two compared methods return an instance of Context. If the Context are different, so each of them serves?

1 answer

2

When using getContext(), you are referring to the context of Activity current, and when using getApplicationContext() you are referring to the context of the application as a whole.

In short:

  1. getApplicationContext() is the context related to the application lifecycle

  2. getContext() is related to the life cycle of Activity

They are different objects, so the result of your equals will be fake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.