I am finding the available memory leaks in my Android application, LeakCanary always says that AppOpsManager OnOpChangedListener callback Function has Leaks for MainActivity. I searched a lot on google and SF but did not find any solution for this. Below is my code, Please help to solve this memory leak.
@Override
protected void onCreate(Bundle savedInstanceState) {
appOpsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
appOpsManager.startWatchingMode(AppOpsManager.OPSTR_GET_USAGE_STATS, getApplicationContext().getPackageName(), usageOpListener);
}
private final AppOpsManager.OnOpChangedListener usageOpListener = new AppOpsManager.OnOpChangedListener() {
@Override
public void onOpChanged(String op, String packageName) {
if (packageName == null || getApplicationContext().getPackageName().equals(packageName)) {
if (AppOpsManager.OPSTR_GET_USAGE_STATS.equals(op)) {
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
getApplicationContext().startActivity(myIntent);
}
}
}
};
@Override
protected void onDestroy() {
appOpsManager.stopWatchingMode(usageOpListener);
}
I believe (although you haven't shown it) that the problem is:
usageOpListener) to another object that you obtained indirectly through the system locator service (appOpsManager) during your class'onCreate.YourActivity#OnOpChangedListeneris now a hard reference inside theAppOpsManager.I'd move the start/stop watching code to onStart/onStop respectively.