0

I have an Activity:

public class MyActivity extends Activity {

    @Override
    protected void onDestroy() {
// TODO: send event to other class
    }
}

and a separate class:

    public class MyClass{
        MyClass(Context context){
          // I have the context of activity
        }

// This needs to be called by MyActivity in all other instantiates
        void onActivityDestroy(){

        }
    }

MyClass is instantiated in other places and I want onActivityDestroy to be called in those instantiates. The place where MyClass is instantiated is not accessible.

I am looking for a solution that uses interfaces, listener, messages... but not static fields.

chris
  • 313
  • 2
  • 12
  • Why don't you call MyClass cs = new MyClass(); cs.onActivityDestry(); in your activty onDestroy() method. – Rishi Oct 19 '16 at 00:39
  • The MyClass is instantiated in other place and I need to run onActivityDestroy there. Not in the instantiates created by me. – chris Oct 19 '16 at 00:50
  • I don't think that's what the desired behavior is, they want to call the onDestroy method of MyActivity, not MyClass. – Glen Pierce Oct 19 '16 at 00:51
  • You might want to ask how to get the instance of MyActivity from within the constructor of MyClass. Look here: http://stackoverflow.com/questions/9723106/get-activity-instance – Glen Pierce Oct 19 '16 at 00:55
  • That is exactly what I did until now but I want to avoid using "static" and especially avoid static Context. – chris Oct 19 '16 at 00:59
  • Why do you want to avoid using static? – Glen Pierce Oct 19 '16 at 01:52
  • I recently [answered](http://stackoverflow.com/questions/39948709/android-custom-listener-for-an-event/39948968#39948968) a question on using a custom listener to get notified on an `Activity`'s event. Take a look, might be helpful. – Onik Oct 19 '16 at 03:37
  • @Glen Pierce - My app is getting bigger and using static everywere makes it very hard to keep working on it – chris Oct 19 '16 at 12:17

1 Answers1

0

You can maintain the list of MyClass instances at application level then access that list in OnDestroy method of activity. And execute onActivityDestroy() version of each instance.

You should maintain list of instances in your Application class, whenever MyClass instance is created, you push that instance to the list maintained at Application Class

// this is to push the MyClass instance.
Context.getApplication().getMyClassInstanceList().add(new MyClass());

public class MyActivity extends Activity {

  @Override 
  protected void onDestroy() { 
    List<Myclass> myClassObjects = Context.getApplication.getMyClassInstaceList();

    for(Myclass myclass : myClassObjects)
     {
          myclass.onActivityDestroy();
     }
   }
 }
Pavan
  • 819
  • 6
  • 18