Question

I have an android application project. I have created a library project and added reference in the application project. Now I need to call/access certain functions/class/methods that is there in the application project from the library project. How can I do that ?

Was it helpful?

Solution

Create an interface in the library that defines the functions you would like the library to call. Have the application implement the interface and then register the implementing object with the library. Then the library can call the application through that object.

In the library, declare the interface and add the registration function:

public class MyLibrary {
  public interface AppInterface {
    public void myFunction();
  }

  static AppInterface myapp = null;

  static void registerApp(AppInterface appinterface) {
    myapp = appinterface;
  }
}

Then in your application:

public class MyApplication implements MyLibrary.AppInterface {
  public void myFunction() {
    // the library will be able to call this function
  }

  MyApplication() {
    MyLibrary.registerApp(this);
  }
}

You library can now call the app through the AppInterface object:

// in some library function
if (myapp != null) myapp.myFunction();

OTHER TIPS

You can just create the object of that particular class and then you can directly call that method or variable.

class A{
  public void methodA(){
    new B().methodB();
    //or
    B.methodB1();
  }
}

class B{
  //instance method
  public void methodB(){
  }
  //static method
  public static  void methodB1(){
  }
}

Don't forget to import the necessary packages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top