excluding src\main\resources from source folders in IntelliJ build

Real quick… I recently switched from Eclipse to IntelliJ, and one thing that’s been annoying me is that IntelliJ keeps putting the src\main\resources folder of my Android project into its list of source folders.  Removing it only helps temporarily; it gets restored again later (I think when I build from the “maven projects” window).

Solution: exclude this folder at the compiler level, in the project settings.  File->Settings->Compiler->Excludes.

Credit for this solution goes to Sergey Evdokimov, who posted it here.

App Crashers!

device-2013-01-17-111315When 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:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fizzbuzz.appcrasher"
    android:sharedUserLabel="@string/app_name"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <permission android:name="com.fizzbuzz.appcrasher.CRASH_APPS" />

    <uses-permission android:name="com.fizzbuzz.appcrasher.CRASH_APPS" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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:

        <activity
            android:name=".CrashActivity"
            android:permission="com.fizzbuzz.appcrasher.CRASH_APPS" >
            <intent-filter>
                <action android:name="com.fizzbuzz.appcrasher.CRASH" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

Maven enforcer plugin vs. dependencyManagement

I recently found myself in a situation where I needed to detect whether my maven dependencies, both direct and indirect (transitive), were resolving to inconsistent versions.

For example, let’s say that artifact A depends on B and C, and B also depends on C.  When building A, I want to know if it is picking up two different versions of C, one directly, and one transitively through B.

As with all Maven problems, “there’s a plugin for that” — in this case, the maven-enforcer-plugin.  It has a variety of interesting rules, but the one that addresses the need I was having is called “dependencyConvergence”.

So, I plugged it in to a top-level parent POM, so I could use it in all my projects:

<project>
  ...
  <build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.1.1</version>
        <executions>
          <execution>
            <id>enforce</id>
            <configuration>
              <rules>
                <DependencyConvergence />
              </rules>
            </configuration>
            <goals>
              <goal>enforce</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
    ...
  </build>
  ...
</project>

I use Eclipse with m2e, and I wanted this enforcement to happen in my Eclipse builds, too, so I also added:

<project>
  ...
  <build>
    ...
    <pluginManagement>
      <plugins>
        <pluginExecution>
          <pluginExecutionFilter>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-enforcer-plugin</artifactId>
            <versionRange>[1.0,)</versionRange>
            <goals>
              <goal>enforce</goal>
            </goals>
          </pluginExecutionFilter>
          <action>
            <execute />
          </action>
        </pluginExecution>
      </plugins>
    </pluginManagement>
    ...
  </build>
...
</project>

I ran a build, and sure enough, I did have some mismatches.  This is a really handy plugin -- I have a decent number of my own artifacts involved, plus a variety of 3rd party ones that    show up frequently in my projects, and with all of them getting updated pretty regularly, it's pretty tough to keep track of everything.

In one case where I had a mismatch, I decided to resolve the problem by moving the specification of C's version up to a parent POM shared by A and B.  Two options occurred to me:

1) I could specify a property like

<c.version>1.2.3</c.version>

and have A's and B's POMs use that inherited property in their definitions of the C dependency.  Or,

2) I could put an entry for C into the parent POM's dependencyManagement section:

<dependencyManagement>
  <dependencies>
    <dependency>
     <groupId>org.foo</groupId>
     <artifactId>c</artifactId>
     <version>1.2.3</version>
    </dependency>
  </dependencies>
</dependencyManagement>

and omit C's version from A's and B's POM.

I tried #2 first, since it seemed a little simpler.  As a first step, I added the dependencyManagement entry to the parent POM and removed the version number for C from A's POM, then ran a build.  Guess what:  maven-enforcer-plugin stopped complaining!  But wait, I didn't change B's POM yet; I should still have a discrepancy, shouldn't I?  I thought that all dependencyManagement did was specify default versions for descendant POMs that omitted the version for that dependency.  I checked my Maven: The Definitive Guide book to see if there was more to it.  Nope, no mention of any other purpose or side effects.  I checked the Sonatype web site's description, in case it was more detailed.  Nope.  Hmm.  Then I went to the horse's mouth, the Apache docs, which say:

Dependency management - this allows project authors to directly specify the versions of artifacts to be used when they are encountered in transitive dependencies or in dependencies where no version has been specified. In the example in the preceding section a dependency was directly added to A even though it is not directly used by A. Instead, A can include D as a dependency in its dependencyManagement section and directly control which version of D is used when, or if, it is ever referenced.

[Note: that page is worth a detailed read; it has some good examples which helped firm up my understanding.]

Interesting.  So the version specified in dependencyManagement serves as a default value if none is specified in a descendant POM (but doesn't override the value in a descendant POM if one is specified).  However, it does override a specified value in a transitive dependency.  Because of this behavior, the version of C in B's POM was being overridden, and therefore maven-enforcer-plugin didn't detect the discrepancy.

This dependencyManagement behavior has pros and cons.  On one hand, you can use it to silence the maven-enforcer-plugin in situations where you can't get all the artifacts involved to use the same version (as might be the case if there are 3rd party artifacts involved).  Of course, if you do that, you're taking a risk that the things could go awry at runtime, if the version you specify in dependencyManagement is incompatible in some way with an artifact that had wanted to use a different version.  But sometimes you don't have a choice, and in this situation you should most likely choose the highest of the requested versions, since it's possible that it contains bug fixes or features needed by the artifact that requested it.

The downside of using dependencyManagement willy-nilly as a DRY technique is precisely that maven-enforcer-plugin will no longer give you a heads up about those discrepancies.

So what I'm doing now is this:

  • I don't put dependencies in the dependencyManagement section of my top-level POM.  I want to be alerted by maven-enforcer-plugin when I've got mismatches.  Instead, I use version properties, as mentioned in my approach #1 above.
  • When maven-enforcer-plugin notifies me of discrepancies, I try to see if I can get the artifacts involved to use the same version of the divergent dependency.  If all the dependencies involved are in my own artifacts, I try to get them aligned on the same version of the dependency.  If some artifacts are mine and some are from 3rd parties, I try to align my dependences with the 3rd parties, and/or look for other versions of the 3rd party artifacts that have dependency versions that align with each other, and my code.
  • If after doing the above, I still have unresolvable discrepancies, I choose what I think is the "best fit" version of the problematic artifact and specify that in the pluginManagement section of the project POM where maven-enforcer-plugin reported the problem (not in my top-level POM).  I add a comment to the dependency declaration in that POM noting the issue and the workaround, so that in the future, should I upgrade to a newer version of the dependency, I'll see the note and can revisit whether the discrepancy can possibly then be resolved.

Connecting to an app engine development server from remote clients

OK, I’m writing this down just in case I run into again the future, because I just spent HOURS tearing my hair out before finding the solution.  Maybe it will help someone else someday, too.

I recently messed around with a whole bunch of configuration-related stuff for my Google App Engine app, requiring me to reestablish my my Eclipse run configuration parameters for executing my app in the development server.  In the past, I had set up port forwarding rules in my router, so that I could hit my app running in my dev server from remote clients like browsers running on other machines, from my client Android app, etc., and it had been working fine.

As is so often the case, after making configuration changes, there is a hill to be re-climbed in order to get everything working again.  In my case, although I could access my app in the dev server from clients running on the same machine, my remote clients could not connect.  I checked my port forwarding rules in my router — they were still there.  I tested them using PFPortCheck tool, and it verified the ports were forwarding correctly.

I turned off my firewall; nope, that’s not the problem.

I rebooted.  Nope.

I power cycled my router and my cable modem (obviously getting desperate here, since I’d already verified that port forwarding wasn’t the issue, but I’ve also found that sometimes challenging your assumptions helps).  But nope.

I tried different ports.  I checked to make sure there weren’t other apps listening on the same port and stealing the requests.  Nope, nope.

I set up Fiddler in reverse-proxy mode, and get this — it started working.  That is, with my dev server listening to port 8080 (the forwarded port) and Fiddler listening on 8888 (also forwarded), my outside requests to 8888 were being picked up by Fiddler, rerouted to 127.0.0.1:8080, and successfully received by my app.  Damn, a Heisenbug. OK, interesting, but still frustrating — why did that work, and what does it tell me about the problem?

After much Googling and cursing, I eventually stumbled across the culprit.  I needed to provide an “–address=…” argument in the run configuration’s command line, to tell the server to listen for connections to addresses other than 127.0.0.1.  After setting this argument to the value of my externally-visible IP address (see WhatsMyIP), I was back in business!

Ugh.

[follow-up: if you specify the --address argument as 0.0.0.0, you can connect from remote clients using the externally-visible IP address, and still connect locally using 127.0.0.1]

Capturing incoming requests to your Google App Engine development server, using Fiddler

I’m working on an app the leverages Google App Engine, and I recently was stumped trying to figure out how to use Fiddler to capture incoming HTTP request to my server when running in development mode, when those requests were coming from another machine.  I’m jotting this down to save others from the hair-pulling I went through.

  1. Change the run/debug configurations in Google Plugin for Eclipse so that the development server uses some port other than 8888.  In my case, I changed it to 8080.  The problem with 8888 is that Fiddler wants to use that port, too.  I tried changing the port that Fiddler listens on, in its options dialog, but it didn’t work for me.
  2. Set up port forwarding on your router, so that the port your development server is listening to is being forwarded to your development machine.
  3. Follow the instructions at http://www.fiddler2.com/fiddler/help/reverseproxy.asp to set up Fiddler as a remote proxy, but be sure to use option #2 (setting up a custom rule).  The registry approach doesn’t seem to work for requests coming in from another machine.
  4. Ensure the external machine making requests to your development server is using the externally-visible IP address for your machine (see whatsmyip.org) and port 8888.  If it uses port 8080, the request will still go to your server, but Fiddler won’t capture it.

Note: I have found that there can be some flakiness in getting this setup to take effect.  I haven’t figured out exactly what the trick is, whether it’s restarting Fiddler multiple times, or simply waiting for some cached value somewhere to time out, …  If somebody solves that part of the puzzle, please let me know.

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.

Version-tolerant StrictMode wrapper for Android

So, you want to start using StrictMode in your Android app, but you need it to run (that is, not crash) on pre-2.3 versions of Android.  A wrapper class seems like the way to go, and there are a couple of solutions floating around the web, but they didn’t quite work like I wanted, so I’ve rolled my own, with inspiration from the Android Developers Blog post entitled “Have your (Cup)cake and eat it too“, which was written by Adam Powell and outlines the “lazy loading” strategy I use here.  My version has the following characterstics:

  • In the code that interacts with the wrapper, there is no extra stuff like try/catch blocks or “if (strictmodeavailable)”
  • The caller can easily make a temporary change to a thread or VM policy at runtime in order to bracket an existing violation
  • The check for debug mode is encapsulated within the wrapper

The solution involved three wrapper interfaces – one for StrictMode, and two more for ThreadPolicy and VmPolicy. There are two implementations of the StrictModeWrapper interface, one for use on Gingerbread or later versions, which passes through to the real StrictMode, and one that’s a noop version for pre-Gingerbread versions. The Gingerbread version of the StrictMode wrapper also makes use of Gingerbread wrappers for ThreadPolicy and VmPolicy.

In practice, it works as follows.  First, wherever you want to initialize StrictMode (e.g. in your Application subclass’ OnCreate() method), you do this:

VersionedStrictModeWrapper.getInstance().init(this);

StrictMode has some convenience methods like allowThreadDiskReads() and allowThreadDiskWrites(), which let you temporarily permit actions that would otherwise  violate the policies you’ve established.  This is useful when you are calling into some other code that you don’t control, or when you consciously decide to do something that violates those policies.  After you’ve finished doing the offending action, you can restore the original policies with setThreadPolicy().  To make this type of interaction possible, I wrote wrappers for the ThreadPolicy and VmPolicy classes also.  Note: StrictMode doesn’t have an allowThreadNetwork() convenience function, but I added one in my wrapper, since I encountered a need for it.

Here’s an example of adjusting the policy temporarily using the wrappers:

// the call below to setContentView will trigger StrictMode disk read and disk write
// violations because the WebView accesses a WebViewDatabase. So, bracket the call
// to setContentView with calls to first permit those actions, and then afterward,
// restore the policy permissions that were previously in place.
StrictModeWrapper strictMode = VersionedStrictModeWrapper.getInstance();
ThreadPolicyWrapper origPolicy = strictMode.allowThreadDiskReads();
strictMode.allowThreadDiskWrites();

setContentView(R.layout.my_web_view); // creates a WebView

strictMode.setThreadPolicy(origPolicy);

Note: since the noop wrapper just returns null for the policy objects returned by allowThreadDiskReads() and allowThreadDiskWrites(), it’s not safe to do anything with them except pass them back in a later call to setThreadPolicy(), but that meets my use cases at the moment. To make things safer, the implementation could be extended with noop versions of the policy wrapper interfaces also.

OK, without further ado, here’s the whole shebang.  Feedback is very welcome.

package com.fizzbuzz.android.versionutil;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.os.StrictMode.VmPolicy;

import com.fizzbuzz.android.versionutil.VersionedStrictModeWrapper.StrictModeWrapper.ThreadPolicyWrapper;
import com.fizzbuzz.android.versionutil.VersionedStrictModeWrapper.StrictModeWrapper.VmPolicyWrapper;

public class VersionedStrictModeWrapper {

	public interface StrictModeWrapper {
		public void init(Context context);

		public ThreadPolicyWrapper allowThreadDiskReads();

		public ThreadPolicyWrapper allowThreadDiskWrites();

		public ThreadPolicyWrapper allowThreadNetwork();

		public void setThreadPolicy(ThreadPolicyWrapper wrapper);

		public void setVmPolicy(VmPolicyWrapper wrapper);

		public static interface ThreadPolicyWrapper {
		}

		public static interface VmPolicyWrapper {
		}
	}

	static public StrictModeWrapper getInstance() {
		StrictModeWrapper wrapper = null;
		final int sdkVersion = Build.VERSION.SDK_INT;
		if (sdkVersion >= Build.VERSION_CODES.GINGERBREAD) {
			wrapper = new GingerbreadStrictModeWrapper();
		}
		else {
			wrapper = new NoopStrictModeWrapper();
		}
		return wrapper;
	}

	static class NoopStrictModeWrapper implements StrictModeWrapper {
		@Override
		public void init(final Context context) {
		}

		@Override
		public ThreadPolicyWrapper allowThreadDiskReads() {
			return null;
		}

		@Override
		public ThreadPolicyWrapper allowThreadDiskWrites() {
			return null;
		}

		@Override
		public ThreadPolicyWrapper allowThreadNetwork() {
			return null;
		}

		@Override
		public void setThreadPolicy(final ThreadPolicyWrapper wrapper) {
		};

		@Override
		public void setVmPolicy(final VmPolicyWrapper wrapper) {
		};

	}

	static class GingerbreadStrictModeWrapper implements StrictModeWrapper {
		@Override
		public void init(final Context context) {
			if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
				StrictMode.enableDefaults();
			}
		}

		@Override
		public ThreadPolicyWrapper allowThreadDiskReads() {
			return new GingerbreadThreadPolicyWrapper(StrictMode.allowThreadDiskReads());
		}

		@Override
		public ThreadPolicyWrapper allowThreadDiskWrites() {
			return new GingerbreadThreadPolicyWrapper(StrictMode.allowThreadDiskWrites());
		}

		@Override
		public ThreadPolicyWrapper allowThreadNetwork() {
			ThreadPolicy origPolicy = StrictMode.getThreadPolicy();
			ThreadPolicy newPolicy = new ThreadPolicy.Builder(origPolicy).permitNetwork().build();
			StrictMode.setThreadPolicy(newPolicy);
			return new GingerbreadThreadPolicyWrapper(origPolicy);
		}

		@Override
		public void setThreadPolicy(final ThreadPolicyWrapper wrapper) {
			StrictMode.setThreadPolicy(((GingerbreadThreadPolicyWrapper) wrapper).getPolicy());
		}

		@Override
		public void setVmPolicy(final VmPolicyWrapper wrapper) {
			StrictMode.setVmPolicy(((GingerbreadVmPolicyWrapper) wrapper).getPolicy());
		}
	}

	static class GingerbreadThreadPolicyWrapper implements ThreadPolicyWrapper {
		private final ThreadPolicy mPolicy;

		public GingerbreadThreadPolicyWrapper(final StrictMode.ThreadPolicy policy) {
			mPolicy = policy;
		}

		public StrictMode.ThreadPolicy getPolicy() {
			return mPolicy;
		}
	}

	static class GingerbreadVmPolicyWrapper implements VmPolicyWrapper {
		private final VmPolicy mPolicy;

		public GingerbreadVmPolicyWrapper(final StrictMode.VmPolicy policy) {
			mPolicy = policy;
		}

		public StrictMode.VmPolicy getPolicy() {
			return mPolicy;
		}
	}
}

When using this code on pre-honeycomb devices, you’ll see stuff like the following in your logcat output, which is harmless:

Could not find class 'android.os.StrictMode$ThreadPolicy$Builder', referenced from method [...]
VFY: unable to resolve static method 11475: Landroid/os/StrictMode;.allowThreadDiskWrites ()Landroid/os/StrictMode$ThreadPolicy;

For comparison, here are some other approaches to the problem I’ve encountered:

  • Manfred Moser wrote a blog post describing a solution that leverages the fact that a runtime exception is thrown if the StrictMode class cannot be loaded: Android StrictMode for all platform versions
  • Dave McLean offered a similar approach that encapsulated the FLAG_DEBUGGABLE check in the wrapper’s init() method in this StackOverflow thread (started by Manfred Moser).  It also appears in the book Pro Android 3, which he co-authored.
  • Mark Murphy (author of several Android books, see CommonsWare.com) describes a lazy-loading approach in “The Busy Coder’s Guide to Android Development”.  His approach, which hews closely to the design described in the Android Developers Blog post mentioned earlier, uses an abstract base class with a static init() method that instantiates one of two static inner classes (depending on the value of SDK_INT) that extend the outer class.  [Since it appears we came at the problem from the same viewpoint, I intend to study Mark's approach a bit more.]

The code appearing in  this article is available under the terms of the Apache License, v2.0.