从库项目中调用android应用程序项目中的辅助函数

时间:2014-03-08 07:29:51

标签: function android library-project

我有一个Android应用程序项目。我创建了一个库项目并在应用程序项目中添加了引用。现在我需要调用/访问库项目中应用程序项目中的某些函数/类/方法。我怎样才能做到这一点 ?

2 个答案:

答案 0 :(得分:11)

在库中创建一个接口,用于定义您希望库调用的函数。让应用程序实现接口然后用库注册实现对象。然后库可以通过该对象调用应用程序。

在库中,声明接口并添加注册功能:

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

  static AppInterface myapp = null;

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

然后在你的申请中:

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

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

您的库现在可以通过AppInterface对象调用该应用程序:

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

答案 1 :(得分:0)

您可以创建该特定类的对象,然后直接调用该方法或变量。

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

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

不要忘记导入必要的包。

相关问题