Workaround for accessing the non-stationary method of an element from a static inner class

I have this non-static inner class that causes a memory leak because it contains an implicit reference to the wrapper class:

private class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub { @Override public void onScheduleUpdatedEvent() throws RemoteException { updateCalendar(); } } 

To prevent it from leaking, I need to make it static:

 private static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub { @Override public void onScheduleUpdatedEvent() throws RemoteException { updateCalendar();-> Compiler error - trying to access a non-static... } } 

It is not possible to make updateCalendar() static, because in it I get access to other non-static variables, and this becomes a mess. What should I do?

+5
source share
2 answers
 private static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub { final WeakReference<Object> obj; //change <Object> to whatever type it is. CalendarScheduleUpdatedEventListener(Object x) { this.obj = new WeakReference<>(x); } @Override public void onScheduleUpdatedEvent() throws RemoteException { Object o = obj.get(); if (o == null) { //because a WeakReference will be null if it has been garbage collected. return; //or throw some exception } o.updateCalendar(); } } 
+4
source

You need to pass a reference to an instance of your outer class. And you need to make your static class public.

 public static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub { @Override public void onScheduleUpdatedEvent(final TheOuterClass instance) throws RemoteException { instance.updateCalendar(); } } 
+6
source

Source: https://habr.com/ru/post/1240171/


All Articles