Passing Activity Context to constructors to use internally - is this bad

后端 未结 3 1242
情话喂你
情话喂你 2021-02-04 01:52

Is it bad practice to pass the Context to a constructor and save it as a private variable for internal use? The other option is to pass the Context as a parameter to methods th

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 02:12

    It depends on the lifetime of your object. If you're sure the Object will only ever be used internally by your Activity you'd be OK passing the Context to the constructor, otherwise don't pass the Context in.

    If an Object has a reference to the Context this will stop the Activity being Garbage Collected, and since an Activity has references to all its views this means you can easily leak a lot of memory very quickly.

    It's easy to catch yourself out here since things like device rotations cause Activities to be re-created and it's easy to hang on to an Object without realising.

    So it's probably best to be on the safe side and pass in the Context as and when you need it.

提交回复
热议问题