Is it safe to save the app context to a static variable in Android?

前端 未结 5 1244
闹比i
闹比i 2020-12-03 04:39

I know that usage of static variables on Android is quite risky, especially if you reference them to activities. However, if I have a class that extends Application (let\'s

5条回答
  •  悲&欢浪女
    2020-12-03 05:08

    is it safe to save the app context to a static variable?

    Presently, yes, it appears to be safe, though I would not have getAppContext() return Context, but instead return App or Application.

    That being said, the fact that the core Android team did not set it up this way in the first place suggests that perhaps there may be hidden issues of which we are unaware, or that in the future this approach may introduce problems.

    As the acronym of the saying goes, YMMV. :-)


    EDIT

    if so , is it also safe for any other class to have any kind of reference to the application context ?

    I have no idea what you mean by "safe" here.

    but if i use multiple processes , i will get totally different references to App class on each process , right?

    If you use multiple processes, you should be slapped with a trout. But, yes, you should get distinct App instances per process.

提交回复
热议问题