Previously I was using android.app.Fragment which provided ComponentCallbacks2. I am now migrating my app to use androidx Fragment. However it says 'onTrimMemory overrides nothing'. I look and see that androidx Fragment only provides ComponentCallbacks. Is there any way to workaround and get the level int?
Asked
Active
Viewed 442 times
2

RKRK
- 1,284
- 5
- 14
- 18

androidguy
- 3,005
- 2
- 27
- 38
-
Do you need to use this for memory purposes or something different? – Martin Marconcini Jun 21 '19 at 18:53
-
This is actually a great question. I have used onTrimMemory in the past to deal with [some hacky ways to determine when an app goes to the background](https://stackoverflow.com/questions/4414171/how-to-detect-when-an-android-app-goes-to-the-background-and-come-back-to-the-fo) but since that's no longer needed, I'm curious if you're expecting to do something when you receive this (not guaranteed) callback. – Martin Marconcini Jun 21 '19 at 19:04
-
Using it for memory management purposes as it's intended. I would like the `level` to know just how important the notification is; since sometimes I do a couple different things depending on the severity. – androidguy Jun 21 '19 at 21:47
1 Answers
2
You can implement ComponentCallbacks2
in your Fragment
and register it using Context.registerComponentCallbacks
:
public class MyFragment extends Fragment implements ComponentCallbacks2 {
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
context.registerComponentCallbacks(this);
}
@Override
public void onDetach() {
requireContext().unregisterComponentCallbacks(this);
super.onDetach();
}
@Override
public void onTrimMemory(int level) {
}
}

Joe Bloggs
- 1,501
- 2
- 7
- 9