问题
We all know that storing a context object (other than the application context) statically is bad practice because it can lead to memory leaks. But can you store a system service derived from the context object? Such as ConnectivityManager
?
// Is this okay?
static ConnectivityMananger connectivityManager;
...
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
回答1:
I recommend using the application Context
for getting such a system service:
connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
Probably all system services use the application Context
internally, but this approach is incrementally safer, for the cost of an additional method call.
If the system service is using the application Context
, you will not leak a Context
when obtaining a system service. Whether you leak anything else through your use of the system service may vary.
来源:https://stackoverflow.com/questions/54633492/can-storing-a-system-service-statically-lead-to-memory-leaks