将 Android 应用程序转换为库时出现问题

Complications while converting an Android application to a library

我有一个 Android 广泛使用 ApplicationContext 的应用程序(比如 MyApp)。 ApplicationContext 通过扩展 Application 的 class 可用。

class MyApp extends Application {

  static Context mContext = null;

  public void onCreate() {
    mContext = getApplicationContext();
  }

  public static Context getContext() {
    return mContext;
  }
}

我想将此应用程序转换为库并在另一个应用程序(例如 AnotherApp)中使用它。现在我看到 AnotherApp 已经有一个类似的 class,它扩展了 Application 并在其自身的任何地方提供了它的上下文。当我将 MyApp 作为一个库移动到 AnotherApp 时,我的代码将无法再获得 ApplicationContext - 因为在 Manifest (android:name=".AnotherApp")

中只能声明一个 class

使应用程序上下文在库中可用的最佳方法是什么?我不介意进行大量代码更改,但想知道我有哪些选择 - 除了将上下文传递给我库中的每个 api。

库不应该使用 getApplicationCOntext 它是为主程序准备的。

您可以在开始时使用函数传递上下文或将其保存到 class 中的 public 静态变量中。


代码设计注意事项

这完全取决于你想如何使用这个库,这些函数会在主应用程序中使用吗? activity 会被直接调用吗?和一堆其他代码设计类似的东西。

如果您有时需要两个活动,最好的方法是将它们放入单独的应用程序中,并使用 Intent 使一个调用另一个。比如 google 地图和其他内置服务的使用方式。

如果你想在主应用程序中使用你的库函数,你根本不应该创建 activity。相反,您应该创建一个摘要 class,用户可以从中继承并使用您的 class。

我在我的应用程序中做过类似的事情。

确实如此,您将无法在您的图书馆中获取上下文 您将只有 AnotherApp 的上下文 如果你想在你的库中使用上下文,你需要有一些方法可以将你的 AnotherApp 的上下文传递给你的库。

例如

class MyApp extends Application {

static Context mContext = null;

public void onCreate() {
    mContext = getApplicationContext();
    objecofYourLibClass = new MyApp();
    objecofYourLibClass.yourMethod(mContext);
}

}

现在您将能够在您的图书馆中使用上下文。