Android

fb-android-dagger 1.0.6 released

This release includes two new injecting base classes:

  • InjectingAppWidgetProvider
  • InjectingActionBarActivity (suggested by Tyler Chesley)

In addition, InjectingApplication was enhanced with a new addSeedModules() method to facilitate unit testing with test-method-specific dagger modules. See Initialize your Android component’s dagger object graph on a per-method basis in your Robolectric tests for a detailed explanation of how to use this feature.

Finally, InjectingServiceModule's provideApplicationContext() provider method was replaced with provideServiceContext, which seems to make more sense in that, uh... context.

Initialize your Android component's dagger object graph on a per-method basis in your Robolectric tests

{note: this blog entry is about dagger 1}

When writing unit tests for Android applications, my go-to tools are Robolectric, dagger, and Mockito.  The combination covers a lot of ground in terms of providing "stand ins" for a lot of Android system functionality and factoring out dependencies from the objects under test by injecting mocks into them.  In my production code, my components derive from helper classes in my fb-android-dagger library, which takes care of creating object graphs and self-injecting those components during their initialization logic. fb-android-dagger's component base classes allows subclasses (including test classes) to participate in establishing the dagger modules to use when creating the object graph.  Thus, a production component might use a module which provides dependency X, while a test component could subclass from the production component and tack on a test module which overrides the production module and provides a mock X instead.

This all works pretty well, but it has a limitation -- the opportunity to override production modules with test modules exists only at the time that the component's initialization method runs.  In practice, this means that if the different test methods in a test class want different mocks to be injected into the component under test, they need to employ some technique to ensure that (1) the set of modules used to create the object graph is established by code which is specific to the test method (which rules out the @Before method, since it is method-independent), and (2) the component under test doesn't get initialized until after (1).

My usual approach to this problem is to defer initialization (which includes object graph generation and injection) of the component under test until inside the test method (as opposed to the @Before method).  In the test method, I first set up my mocks (which are fields of the test class) to provide the desired behavior, then initialize the component under test.  For the test subclass of my component, I override getModules() to supply a module (with overrides=true) that has provider methods which provide the mocks configured in the test method.  Note that this overriding module class must be non-static to have access to the mocks in the test class.

In the following example, assume that MyBroadcastReceiver is the class of the object under test, and it extends InjectingBroadcastReceiver from fb-android-dagger.


@RunWith(RobolectricTestRunner.class)
public class MyTest {
    private X mockX = Mockito.mock(X.class);
 
    BroadcastReceiver testReceiver = new TestMyBroadcastReceiver();
 
    @Test
    public void onReceive_doesSomethingWhenXIsEnabled() {
        // for this test, I want to simulate an "enabled" X
        Mockito.when(mockX.getEnabled()).thenReturn(true);
 
        // onReceive will build the object graph and inject itself using a provider
        // which returns mockX.
        testReceiver.onReceive(...);
 
        // ... verification logic...
    }
 
    @Test
    public void someMethod_doesSomethingDifferentWhenXIsDisabled() {
        // for this test, I want to simulate a "disabled" X
        Mockito.when(mockX.getEnabled()).thenReturn(true);
 
        // etc.
    }
 
    private class TestMyBroadcastReceiver extends MyBroadcastReceiver {
        @Override
        protected List<Object> getModules() {
            List<Object> result = super.getModules();
            result.add(new MockXModule());
            return result;
        }          
    }
 
    @Module(injects=MyBroadcastReceiver, overrides=true)
    private class MockXModule {
        @Provides
        public X provideX() {
            return mockX;
        }
    }
}

However, this approach doesn't work if you want to tweak the Application-scope object graph on a per-method basis, because Robolectric creates and initializes (and hence injects) the Application object for you implicitly before your test method runs.  Even if you have a test application class that overrides getModules() and adds modules with provider methods that leverage the state of the test object (i.e. using the technique above), it won't work, because getModules() will get called before the test method runs, and therefore the test method will have no opportunity to configure the test object's state prior to injection of the application object.

Robolectric does provide hooks in the form of the TestLifecycleApplication interface, whose beforeTest, prepareTest, and afterTest methods you can implement in your test application class, but they aren't helpful in this case, since they all run after your test application's onCreate() method has already been called (and thus its object graph has already been created and used to inject it).

One workaround to this problem would be to use different test application classes for different methods, using Robolectric 2.4's @Config(application=...) annotation on a per-method basis.  With this approach, you'd need your different test application classes to specify different modules in their getModules() implementations, each hardcoded to provide the desired mock behavior for the corresponding test method.  Note: here we're assuming that MyBroadcastReceiver's dependency on X is satisfied from the Application-scope object graph.


@Test 
@Config(application=TestMyBroadcastReceiverWithXEnabled.class) 
public void onReceive_doesSomethingWhenXIsEnabled() { ... }

@Test 
@Config(application=TestMyBroadcastReceiverWithXDisabled.class) 
public void onReceive_doesSomethingDifferentWhenXIsDisabled() { ... }

private class TestMyBroadcastReceiverWithXEnabled extends MyBroadcastReceiver { 
    @Override protected List<Object> getModules() { 
    List<Object> result = super.getModules();
    result.add(new MockXEnabledModule()); 
    return result; 
    } 
}

private class TestMyBroadcastReceiverWithXDisabled extends MyBroadcastReceiver { 
    @Override protected List<Object> getModules() { 
        List<Object> result = super.getModules(); 
        result.add(new MockXDisabledModule()); 
        return result; 
    } 
}

@Module(injects=MyBroadcastReceiver, overrides=true) 
private class MockXEnabledModule { 
    @Provides public X provideX() { 
        X mockX = mock(X.class); 
        when(mockX.isEnabled()).thenReturn(true); 
        return mockX; 
    } 
}

@Module(injects=MyBroadcastReceiver, overrides=true) 
private class MockXDisabledModule { 
    @Provides public X provideX() {
        X mockX = mock(X.class);
        when(mockX.isEnabled()).thenReturn(false); 
        return mockX; 
    }
}

 

That can get a little unwieldy when you start having combinations of method-specific modules, since each combination would need a different test application subclass.  To avoid that kind of proliferation, I've implemented a subclass of RobolectricTestRunner called InjectingRobolectricTestRunner, which looks for annotations like


@Test 
@With(appModules={MockXEnabledModule.class}) 
public void onReceive_doesSomethingWhenXIsEnabled() { ... } 

and takes care of seeding the annotation-specified modules into the Application object prior to its onCreate() method being called.  This required two small enhancements to InjectingApplication in fb-android-dagger: (a) a new setter method by which the InjectingRobolectricTestRunner can assign the seed modules, and (b) an update to its getModules() method, to add the seed modules into the list it returns.

In some cases, this approach may eliminate the need for test application subclasses altogether, but it works with them just as well -- the annotations establish the method-specific modules, and the test application class' getModules() method tacks on any others that are not method-specific.  As with the first approach described above, note that the test-specific modules must be hardcoded to exhibit the desired method-specific behavior. Here's the code for InjectingRobolectricTestRunner:


public class InjectingRobolectricTestRunner extends RobolectricTestRunner {
    public InjectingRobolectricTestRunner(Class testClass) throws InitializationError { 
        super(testClass); 
    }

    @Override protected Class getTestLifecycleClass() { 
        return InjectingTestLifecycle.class; 
    }

    public static class InjectingTestLifecycle extends DefaultTestLifecycle {

        @Override public Application createApplication(Method method, AndroidManifest appManifest, Config config) { 
            InjectingApplication injectingApplication = (InjectingApplication) super.createApplication(method, appManifest, config);

            List<Object> seedModules = new ArrayList<>();

            if (method.isAnnotationPresent(With.class)) { 
                With with = method.getAnnotation(With.class); 
                for (Class<?> clazz : with.appModules()) { 
                    try { 
                        seedModules.add(clazz.newInstance()); 
                    } catch (InstantiationException e) { 
                        e.printStackTrace(); 
                    } catch (IllegalAccessException e) { 
                        e.printStackTrace(); 
                    } 
                }
            }

            injectingApplication.addSeedModules(seedModules); 
            return injectingApplication; 
        }
    }

    @Qualifier 
    @Target(METHOD) 
    @Documented 
    @Retention(RUNTIME) 
    public @interface With { 
        Class<?>[] appModules(); 
    } 
}


tip: to bind dagger singletons to a particular object graph scope, use injects=

 

{note: this blog entry is about dagger 1}

If you want singleton semantics for injected objects, dagger offers two approaches - you can implement a @Singleton-annotated provider method, or you can implement an @Inject-annotated constructor in a @Singleton-annotated class. The latter approach is obviously a little more concise, but it raises one issue, which is that in an application with multiple object graphs, some of which extend others (e.g. an Activity-scope graph that extends an Application-scope graph), dagger will maintain singletons of those @Singleton-annotated classes in each object graph that is requested to inject one.  So if you've got a @Singleton-annotated Foo class, you could end up with one Foo object shared by objects that are injected via the Activity-scope graph, and another Foo object shared by objects injected via the Application-scope graph.

There are two ways to avoid this.  Let's assume you want only one Foo instance and you want it to be bound to the Application-scope graph.  In your Application module declaration, you could (1) add a @Singleton-annotated provider method for Foo, or (2) include Foo.class in the "injects=" part of your @Module annotation.  When I first read about this, I found it a little confusing, as I thought the "injects=" list was just for enumerating the classes that the module injects into, but some experimentation confirmed that specifying classes to inject has the effect of binding their @Inject-annotated constructor to that module (essentially creating an implicit provider), and thus to the object graph created from it.

Introducing fb-android-dagger - a helper lib for using dagger with Android

A while back, Square released a new dependency injection framework called dagger, emphasizing simplicity and performance (via compile-time code generation rather than runtime reflection). Dagger actually has no Android dependencies and thus can be used in other contexts, but it has gained traction among Android developers. As I started working with it, it quickly became clear that it would be handy to have a set of reusable base classes that integrate dagger with the standard Android components like Application, Service, BroadcastReceiver, Activity, and Fragment. And so, fb-android-dagger was born. I open sourced it about a year ago, and a few people seem to be using it, so it's probably (past) time I introduced it.

Creating object graphs

I'll skip over the dagger basics, as they're explained well on Square's dagger page, but I'll note that a useful implementation pattern that quickly emerged is to have a component base class do the ObjectGraph initialization and injection of "this" in its first lifecycle method (e.g. Activity.onCreate()). To initialize the graph, that code needs the set of applicable dagger modules, so the base class defines a getModules() method which it expects subclasses to override by supplying the modules they want to contribute to the graph.

Here's a typical subclass implementation of getModules():


public class MyActivity extends InjectingActivity {

// ...

    @Override protected List<Object> getModules() {
        List<Object>
        modules = super.getModules();
        modules.add(new MyModule());
        return modules; 
    } 
} 

s you can see, the idea is for the module list to be built cooperatively via the getModule() overrides in the chain of classes deriving from the injecting base class. Each class' getModules() method first gets its superclass' module list, add its own modules to the list and returns the combined list.

fb-android dagger's set of component base classes each implement this mechanism, in a lifecycle method appropriate to the component:

  • InjectingApplication (onCreate)
  • InjectingBroadcastReceiver (onReceive)
  • InjectingService (onCreate)
  • InjectingActivity (onCreate)
  • InjectingFragmentActivity (onCreate)
  • InjectingPreferenceActivity (onCreate)
  • InjectingFragment (onAttach)
  • InjectingListFragment (onAttach)
  • InjectingDialogFragment (onAttach)

In addition, the graphs that fb-android-dagger creates are scoped to their associated components, so the graph created by MyActivityOne is distinct from the graph created for MyActivityTwo. However, it does reuse and extend graphs created by other components, working "outward" from the Application graph:

  • an Application-scope graph is created by InjectingApplication
  • InjectingBroadcastReceiver creates a BroadcastReceiver-scoped graph that extends the Application-scope graph.
  • InjectingServiceReciever creates a Service-scoped graph that extends the Application-scoped graph
  • InjectingActivity, InjectingFragmentActivity, and InjectingPreferenceActivity create Activity-scoped graphs that extend the Application-scoped graph.
  • InjectingFragment, InjectingDialogFragment, and InjectingListFragment create Fragment-scoped graphs that extend their associated Activity's graph.

Helper modules

fb-android-dagger also provides a set of dagger modules and qualifier annotations to facilitate injection of objects relevant to their component type.

For example, a class injected by an Activity-scope graph could get the Activity's context and the Application context injected like so:


class Foo1 { 
    @Inject @Application Context appContext;
    @Inject @Activity Context activityContext; // ... 
}

A class can also access relevant components themselves, directly:


class Bar { 
    @Inject Application theApp;
    @Inject Activity myActivity; 
    @Inject Fragment myFragment; // ... 
}

Feel free to give a try!

Source is on Github

Maven users can download from Maven Central:


<dependency> 
	<groupId>com.fizz-buzz</groupId>
    <artifactId>fb-android-dagger</artifactId>
    <version>1.0.3</version> 
</dependency> 


watch out when using Activity.getPreferences()!

The Android SDK has a handy little method for getting SharedPreferences -- the Activity class has a getPreferences() method that implicitly opens/creates a preferences file named after the simple class name of the Activity (e.g. "MyActivity"). Cool, it works.  Ship it.

OK, now in version 2, you add a new Activity called MyOtherActivity, and want to access those same preferences.  Hmm, you can't use getPreferences() in MyOtherActivity; that would use a different filename.  So, you have to use (from the Context class) getSharedPreferences(MyActivity.class.getSimpleName(), ...) instead.

A little ugly.  But wait, it gets worse.

Maybe later, you decide to rename MyActivity to ABetterNameForMyActivity.  Now things are really a nuisance, because you can't use getPreferences() inside MyActivity anymore, and the hack in MyOtherActivity won't work, either (in an upgrade scenario, the new version of the app won't use the preference file left over from the previous version).

You can replace both usages to use Context.getSharedPreferences("MyActivity", ...), i.e. explicitly specify the name of the no-longer-existing activity, but that's going to be pretty confusing to the next guy who looks at the code.

So, to avoid all this, my recommendation is to create a helper class right from the beginning that encapsulates the name of the preference file (which would be unrelated to any particular Activity).  This would also be a good place to define static Strings for the preference value names used when getting and setting preference values.  Something like this (a little crude, but you get the idea):


public class SharedPrefs { 
    public static String PREF_VALUE1 = "value1";
    public static String PREF_VALUE2 = "value2";

    private static String prefsFileName = "prefs"; 
    private SharedPreferences prefs;

    public SharedPrefs(Context context) { 
        prefs = context.getSharedPreferences(prefsFileName, Context.MODE_PRIVATE); 
    }

    public SharedPreferences getPreferences() { 
        return prefs; 
    }
}

App Crashers!

When I was a little kid, I had a great-uncle whom the family called "George With The Hat", to distinguish him from another (hat-less) great-uncle also called George.  George With The Hat was a farmer, and raised sheep.  I remember that when visiting him, he would go out to the pasture to feed the sheep, and as he approached, he would call out "baaa!", and the sheep would all reply in unison and come running over to him.  I thought that was cool, but when I tried it, they ignored me. What does this have to do with software?  Bear with me.

I've integrated my Android app with a crash reporting mechanism, so that I can find out about problems my users encounter.  I use ACRA, which I've tied in with BugSense, but there are others like Crittercism, Flurry, HockeyApp, etc.

I wanted to have an easy way to test that the crash-reporting mechanism was working in release builds of my app, but I didn't want to have to put some obscure UI affordance into the app to trigger a crash.

So, I built a separate little "App Crasher" app.  All it does it show a button that, when pressed, sends out an intent with a custom action.  Then, in my app that contains the crash reporting logic, I implemented a simple activity that intentionally causes a crash in its onCreate() method.  In the manifest, that activity registers an intent filter to receive the intent sent by the App Crasher. As an extra precaution (here's where George With The Hat comes in), I implemented a custom permission that the "crash-ee" requires of the "crash-er" as part of the intent filtering.

It's all pretty simple, but handy, and it demonstrates how to use intents with custom verbs and permissions to communicate between apps.

Without further ado, the code:

In the App Crasher app, the main activity does a setContentView() on a layout containing a button with the ID "boom", looks up that button via findViewById(), and sets an onClickListener on it that calls startActivity(), specifying the custom action.


public class MainActivity extends Activity {

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.boom);
        button.setOnClickListener(new View.OnClickListener() { 
            @Override public void onClick(View v) { 
                try { 
                    startActivity(new Intent("com.fizzbuzz.appcrasher.CRASH"));
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(MainActivity.this, "No apps found that want to crash :-(", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

The App Crasher manifest declares a custom permission that the receiving app's intent filter will require of intent senders:

 

In the app where I want to receive the intent and produce a crash, I added a simple activity:


public class CrashActivity extends Activity { 
    @Override protected void onCreate(Bundle savedInstanceState) { 
        int i = 1 / 0; // boom! 
    }
} 

... and in that app's manifest, I declared the activity and an intent filter for it, specifying the custom permission and the custom action:


Eliminating the lag after Android gesture completion

Thought I'd write this up quickly, since I ran into it not too long ago, and then I saw someone asking about it recently online... If you're implementing some gesture recognition in your Android app, one of the first things you'll notice after you get it basically working, is that there's an annoying and mysterious delay between the time that you finish drawing the gesture, and the time that the processing of that gesture begins (i.e. when GestureOverLayView.onGesturePerformed gets called).

This is caused by the so-called "fade offset".  If you're showing the gesture on the screen, then during this time period, the drawn gesture fades away.  However, if you're not showing it, it's just a waste of time.

To eliminate this lag (the default duration of which is 400 milliseconds), call the following methods on your GestureOverlayView:

setFadeEnabled(false) setFadeOffset(0)

or use the equivalent android:fadeOffset and android:fadeEnabled properties in your view's layout XML.