Vignesh
Vignesh

Reputation: 35

Complications while converting an Android application to a library

I had an Android application(MyApp, say) that used ApplicationContext extensively. The ApplicationContext was made available via a class that extended Application.

class MyApp extends Application {

  static Context mContext = null;

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

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

I would like to convert this application to a library and use it in another application ( AnotherApp, say). Now I see that AnotherApp already has a similar class that extends Application and gives its context everywhere within itself. When I move MyApp as a library into AnotherApp, my code will not be able to get ApplicationContext anymore - as only one class can be declared in Manifest (android:name=".AnotherApp")

What is the best way to make application context available within library? I do not mind making extensive code changes, but would like to know options I have - other than passing context to every api in my library.

Upvotes: 2

Views: 290

Answers (2)

user4571931
user4571931

Reputation:

I have done similar stuffs in my Application.

Its true you will not able to get context in your library You will have context of only AnotherApp If you want to use Context in your library in that case you need to have some method which can pass your AnotherApp's context to your library.

For example

class MyApp extends Application {

static Context mContext = null;

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

}

Now you will able to use context in your Library.

Upvotes: 0

AbdealiLoKo
AbdealiLoKo

Reputation: 3357

A library should never use the getApplicationCOntext it is meant for the main program.

you can pass the context using a function or save it into a public static variable in your class in the beginning.


Note about code design

This completely depends on how you want to use the library, will the functions be used in the main app ? Will the activity be directly called ? and a bunch of other code design things like that.

If you want two activities sometimes the best way it to make them into separate applications and make one call the other using an Intent. Like how google maps and other inbuilt services are used.

If you want to use your library's function in the main application, you should not be creating an activity at all. Rather you should make an abstract class that the user can inherit from and use your class through.

Upvotes: 1

Related Questions