Android Carbonara

Android programming can be very frustrating. At some point, I got so frustrated that I googled for “android context s***s” and found a lot of like minded people. But why is it that Android development gets so annoying so fast?

So far, I was able to determine 2 major pain points:

  • Context passing
  • Activity callbacks

These two things alone lead to gigantic activities, stupid Foo(Context context) constructors, memory leaks and a lot of spaghetti code. By fixing one problem however the second one becomes a lot easier to manage.

Context passing

You have a module that creates a displayed String? Then Foo(Context context) should look familiar. Even the stupidest things like reading a color value or localized String or creating a database or calling another module (via Intent) require Context. At some point your complete code looks like:

Foo foo = new Foo(context);
Bar bar = new Bar(context);
Baz baz = new Baz(context);

All these modules will look like:

public class Foo{
public Foo(Context context){this.context = context;}
public static void doSomethingSimple(Context context){...}
public static void doMoreSimpleStuff(Context context){...}
private void do(){...; doSomethingWithContext(this.context);}

The problem with this code is, it not only does look like …. but it also introduces Memory Leaks because you can do something like:

Foo foo = new Foo(this /*I'm an activity*/);

The code itself is perfectly valid since Activity inherits from Context or ContextWrapper. However, Activities have a lifecycle and get destroyed at some point but Foo doesn’t necessarily share the same lifecycle. When Foo keeps the this.context = context; reference, Android will have a hard time destroying the Activity -> memory leak.

Activity callbacks

public void
onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
//spaghetti goes here
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//tomato sauce goes here

Activity callbacks are the modern GOTO statements. Combine them with startActivityForResult() and you will effectively make a function call in line 2500 and get the result in line 19. If one likes to write modular code that can potentially become part of a shared codebase and be re-used in plain Java, or easily tested, this stuff is the hell. Everything is bound to, controlled and dispatched by activities and easily ends up in spaghetti code.

Either beginners are too stupid to grasp these concepts or they are just poorly designed.

If one would want to write for example a simple file scanner which in its core is a general concept (not Android specific) this person would have to pass an Activity to the scanner to request and handle the Manifest.permission.READ_EXTERNAL_STORAGE permission. The module immediately becomes an Android specific module which makes me personally very sad.

Fixing Android

Searching for a solution I went through numerous of stackoverflow posts and the presented solution for the above two problems has probably 10.000 upvotes combined on stackoverflow. The ANDROID FIX requires the use of some unpopular API calls like registerActivityLifecycleCallbacks(), the ResultReceiver class some tricks and static variables.

The solution is not really beautiful but it works. In order to handle the issues one will have to:

  1. Create an Application base class
  2. Create an Activity base class
  3. Create a tracker for permission and activity calls
  4. (Optional) Create a wrapper class to turn all calls that need context into context-less calls

I will just outline the solution here which should give a good idea how to achieve things. If this post get’s a lot of upvotes or feedback it can probably be improved and turned into a github project. In any way feel free to contact me or provide critical feedback.

Application base class

public class AppBase extends Application{
   private Activity currentActivity; //stores activity context
private static Context context; //stores app context
public void onCreate(){
//make applicaton context globally available
AppBase.context = getApplicationContext();
    //track activities, set and clear(!) activity context here
registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks{
        //track and set current activity / context here     

With this code you create an Application base class which has a static field for the application context and another field that holds the context of the current active activity. You can now, from everywhere in your app, call AppBase.getContext() or AppBase.getActivityContext() which completely eliminates context passing.

Source: Activity Context, AppContext

Activity base class

public class ActivityBase extends AppCompatActivity {
public void onRequestPermissionsResult(int rc, String[] p, int[] g) {
super.onRequestPermissionsResult(rc, p, g);
PermissionsHelper.inst().onRequestPermissionsResult(rc, p, g);
  //do the same with activity results

Here, we have the Activity base class: The base class implements the activity callbacks and simply passes them to two helper classes as described below. The caveat is ALL activities need to extend this base class.

Activity callback helper

Now, we only need two helper classes that make calls, receive the result and activate callbacks.

public class PermissionsHelper {
  public void requestPermission(String p, PermissionCallback c){
    //generate or use constant request code for permission p
//store callback e.g. in a map code->callback for later if we have a result for permission p
    Activity requestingActivity = AppBase.getActivityContext(); 
//check permission and make callback or
    //request permission
ActivityCompat.requestPermissions(requestingActivity, new String[]{permission}, requestCode);

This is an example for a class that keeps track of callers and handles permision related activity callbacks. You can find a more comprehensive draft here: Gist

The trick is that we don’t explicitly define the activity to receive the result. Instead, we don’t care and use the Activity that is currently active and which is retrieved through our AppBase as defined above. We can ignore the specific active Activity since all activities should inherit ActivityBase. At some point, whatever Activity is “active” will receive the result and pass it back to our PermissionsHelper.


The PermissionsHelper handles all the Android imposed magic-number-result-code stuff by defining suitable constants and maps them to callbacks. We can now write clean code with maximum Separation of Concerns, the PermissionsHelper can be easily mocked for testing and code can be used outside of the Android platform:

//somewhere we need a permission or result:
PermissionsHelper.getInstance().requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, new PermissionsHelper.PermissionCallback() {
public void permissionGranted() {

We just request a permission, provide a callback and can finally forget about the madness.

For ActivityResults we can pass a ResultReceiver and do not even have to define another helper class. The technique is described here and unfortunately works only with Activities that inherit from ActivityBase. For everything else we should write a helper class.

[Optional] Context-Less Wrapper

Since we can now forget about Context, one can optionally write a wrapper:

public clas EzPz{
  public static String getString(@StringRes int res){
return AppBase.getContext().getString(res);

And from now on request String resources, start Dialogs, get colors etc. the way we would like to do it.