Need Context in Model in MVP

前端 未结 2 803
太阳男子
太阳男子 2020-12-31 09:42

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

2条回答
  •  一生所求
    2020-12-31 10:22

    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.

提交回复
热议问题