Get Android Google Analytics referrer tag

I went ahead and published a dead pixel finder app to play with snooping on the intent. For some reason, when I registered two different broadcast receivers (ie com.google.android.apps.analytics.AnalyticsReceiver and my own), I never received it on my own.

So instead, I registered only my own receiver, process the information, and pass it along to Google Analytics. Don’t know how kosher this is, but it works. Code follows.

public class ZSGoogleInterceptor extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();

        String referrerString = extras.getString("referrer");
        // Next line uses my helper function to parse a query (eg "a=b&c=d") into key-value pairs
        HashMap<String, String> getParams = Utility.getHashMapFromQuery(referrerString);
        String source = getParams.get("utm_campaign");

        if (source != null) {
            SharedPreferences preferences = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            Editor preferencesEditor = preferences.edit();
            preferencesEditor.putString("ga_campaign", source);
            preferencesEditor.commit();
        }

        // Pass along to google
        AnalyticsReceiver receiver = new AnalyticsReceiver();
        receiver.onReceive(context, intent);
    }

}

Then, when your application is actually launched, you can pull the value back out of the shared preferences and pass it along with user signup or whatever. I used the campaign tag for my purposes, but you can grab any parameters you want out of the referrer string created with this tool.

Leave a Comment