Extending Application

一世执手 提交于 2019-11-29 17:26:15
benvd

As far as I know, passing along contexts is not exceptional in Android development. Well, either that or I'm doing it wrong.

I'm not sure if you needed this answered or not, but from a context, you can access the Application object like this:

((MyApplication) context.getApplicationContext()).getMyGlobalVariable();

Your MyApplication class should live throughout the entire application lifecycle, yes.

Also check out this answer.

Passing along Context is fine in Android as long as you pass the correct context. Avoid passing down Activities as context. Use getApplicationContext() instead.

Your Applicationobject and all the data associated with it will persists through the whole life of your application. Even if the app is in background and all the activities get cleared from memory because they are not shown anymore. At what time the application object will be cleared from memory is not very well documented but I think that if your app is in the background and memory is rare the OS may destroy your whole app and therefore also removing the application object from memory.

There is no way to get the application object if you can't access a context. If you only need a reference to the application just pass down the application object, this will minimize the errors that can arise form saving a reference to an activity that is not on screen anymore and leaking the whole activity through this reference.

I don't have any example code but I used it to hold references to some tasks. This enabled me to allow the user to change between activities very fast without making her wait for the tasks to return even if the next activity has to change some states depending on the tasks that are running at the moment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!