I need to use the Context of activity in the model while using MVP in android to get the list of all the installed application.what is the correct way to access the context
Basically, you have the following options:
1) Always pass a Context
to the Model. Whatever event happens in Android, you always have some kind of Context
available. (And your code is invoked only in response to events.)
2) getApplicationContext()
and store it for future use in a static variable.
There are the following gotchas:
An Activity
is a Context
, but if you store a link to an Activity, you get a memory leak. Activities are re-created when for example the screen turns.
The same about contexts passed to BroadcastReceivers and other kinds of Context. All of them have a lifetime, and that lifetime is not what you need for Model.
It is possible that your application is killed and restarted by Android. In this case, some global (static) variables may be set to null. That is, they will be null unless your application happens to write something to them. In particular, a static variable pointing to the application context may become null in one of restart scenarios. Such problems are difficult to test against.